diff --git a/.gitattributes b/.gitattributes index 51a00f8038..78693e2360 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,68 +1,71 @@ .git* export-ignore .hooks* export-ignore .mailmap export-ignore # Set general file size limit on all files * hooks.MaxObjectKiB=1024 *.bat -crlf *.bin -crlf *.blend -crlf *.bmp -crlf *.cpt -crlf *.gif -crlf *.icns -crlf *.ico -crlf *.jpeg -crlf *.jpg -crlf *.mha -crlf *.odg -crlf *.pbxproj -crlf *.pdf -crlf *.plist -crlf *.png -crlf *.ppt -crlf *.pptx -crlf *.raw -crlf *.vtk -crlf *.xcf -crlf *.xpm -crlf -diff *.sh crlf=input *.sh.in crlf=input configure crlf=input cvsrmvend crlf=input imcp crlf=input imglob crlf=input imln crlf=input immv crlf=input imrm crlf=input imtest crlf=input install-sh crlf=input newalpha crlf=input newversion crlf=input remove_ext crlf=input vxl_doxy.pl crlf=input zap.pl crlf=input *.c whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.cpp whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.h whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.cxx whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.hxx whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.txx whitespace=tab-in-indent,no-lf-at-eof copyright=mitk-license hooks.style=KWStyle,uncrustify *.txt whitespace=tab-in-indent,no-lf-at-eof *.cmake whitespace=tab-in-indent,no-lf-at-eof # The Microservices use an apache copyright -Core/Code/CppMicroServices/**/*.c copyright=apache-license -Core/Code/CppMicroServices/**/*.cpp copyright=apache-license -Core/Code/CppMicroServices/**/*.h copyright=apache-license +Core/CppMicroServices/**/*.c copyright=apache-license +Core/CppMicroServices/**/*.cpp copyright=apache-license +Core/CppMicroServices/**/*.h copyright=apache-license + +# This is a file with special test data +Core/CppMicroServices/test/modules/libRWithResources/resources/foo.txt -whitespace # There is no need to check files in the utilities directory for copyright Utilities/** -copyright Applications/PluginGenerator/PluginTemplate/src/**/*.h -copyright Applications/PluginGenerator/PluginTemplate/src/**/*.cpp -copyright Applications/PluginGenerator/ProjectTemplate/Apps/TemplateApp/TemplateApp.cpp -copyright # ExternalData content links must have LF newlines *.md5 crlf=input diff --git a/Core/Code/CppMicroServices/CMake/MacroParseArguments.cmake b/Core/Code/CppMicroServices/CMake/MacroParseArguments.cmake deleted file mode 100644 index 8f61fdc704..0000000000 --- a/Core/Code/CppMicroServices/CMake/MacroParseArguments.cmake +++ /dev/null @@ -1,79 +0,0 @@ -# macro(MACRO_PARSE_ARGUMENTS prefix arg_names option_names) -# -# From http://www.cmake.org/Wiki/CMakeMacroParseArguments: -# -# The MACRO_PARSE_ARGUMENTS macro will take the arguments of another macro and -# define several variables: -# -# 1) The first argument to is a prefix to put on all variables it creates. -# 2) The second argument is a quoted list of names, -# 3) and the third argument is a quoted list of options. -# -# The rest of MACRO_PARSE_ARGUMENTS are arguments from another macro to be -# parsed. -# -# MACRO_PARSE_ARGUMENTS(prefix arg_names options arg1 arg2...) -# -# For each item in options, MACRO_PARSE_ARGUMENTS will create a variable -# with that name, prefixed with prefix_. So, for example, if prefix is -# MY_MACRO and options is OPTION1;OPTION2, then PARSE_ARGUMENTS will create -# the variables MY_MACRO_OPTION1 and MY_MACRO_OPTION2. These variables will -# be set to true if the option exists in the command line or false otherwise. -# -# For each item in arg_names, MACRO_PARSE_ARGUMENTS will create a variable -# with that name, prefixed with prefix_. Each variable will be filled with the -# arguments that occur after the given arg_name is encountered up to the next -# arg_name or the end of the arguments. All options are removed from these -# lists. -# -# MACRO_PARSE_ARGUMENTS also creates a prefix_DEFAULT_ARGS variable containing -# the list of all arguments up to the first arg_name encountered. - -if(NOT COMMAND MACRO_PARSE_ARGUMENTS) - -macro(MACRO_PARSE_ARGUMENTS prefix arg_names option_names) - - set(DEFAULT_ARGS) - - foreach(arg_name ${arg_names}) - set(${prefix}_${arg_name}) - endforeach(arg_name) - - foreach(option ${option_names}) - set(${prefix}_${option} FALSE) - endforeach(option) - - set(current_arg_name DEFAULT_ARGS) - set(current_arg_list) - - foreach(arg ${ARGN}) - - set(larg_names ${arg_names}) - list(FIND larg_names "${arg}" is_arg_name) - - if(is_arg_name GREATER -1) - - set(${prefix}_${current_arg_name} ${current_arg_list}) - set(current_arg_name "${arg}") - set(current_arg_list) - - else(is_arg_name GREATER -1) - - set(loption_names ${option_names}) - list(FIND loption_names "${arg}" is_option) - - if(is_option GREATER -1) - set(${prefix}_${arg} TRUE) - else(is_option GREATER -1) - set(current_arg_list ${current_arg_list} "${arg}") - endif(is_option GREATER -1) - - endif(is_arg_name GREATER -1) - - endforeach(arg ${ARGN}) - - set(${prefix}_${current_arg_name} ${current_arg_list}) - -endmacro(MACRO_PARSE_ARGUMENTS) - -endif(NOT COMMAND MACRO_PARSE_ARGUMENTS) diff --git a/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake b/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake deleted file mode 100644 index a63b6e4d9c..0000000000 --- a/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake +++ /dev/null @@ -1,85 +0,0 @@ -#! Generate a source file which handles proper initialization of a module. -#! -#! This CMake function will store the path to a generated source file in the -#! src_var variable, which should be compiled into a module. Example usage: -#! -#! \verbatim -#! set(module_srcs ) -#! usFunctionGenerateModuleInit(module_srcs -#! NAME "My Module" -#! LIBRARY_NAME "mylib" -#! VERSION "1.2.0" -#! ) -#! add_library(mylib ${module_srcs}) -#! \endverbatim -#! -#! \param src_var (required) The name of a list variable to which the path of the generated -#! source file will be appended. -#! \param NAME (required) A human-readable name for the module. -#! \param LIBRARY_NAME (optional) The name of the module, without extension. If empty, the -#! NAME argument will be used. -#! \param AUTOLOAD_DIR (optional) The name of a directory relative to this modules library -#! location from which modules will be auto-loaded during activation of this module. -#! If unspecified, the LIBRARY_NAME argument will be used. If an empty string is provided, -#! auto-loading will be disabled for this module. -#! \param DEPENDS (optional) A string containing module dependencies. -#! \param VERSION (optional) A version string for the module. -#! \param EXECUTABLE (flag) A flag indicating that the initialization code is intended for -#! an executable. -#! -function(usFunctionGenerateModuleInit src_var) - -MACRO_PARSE_ARGUMENTS(US_MODULE "NAME;LIBRARY_NAME;AUTOLOAD_DIR;DEPENDS;VERSION" "EXECUTABLE" ${ARGN}) - -# sanity checks -if(NOT US_MODULE_NAME) - message(SEND_ERROR "NAME argument is mandatory") -endif() - -if(US_MODULE_EXECUTABLE AND US_MODULE_LIBRARY_NAME) - message("[Executable: ${US_MODULE_NAME}] Ignoring LIBRARY_NAME argument.") - set(US_MODULE_LIBRARY_NAME ) -endif() - -if(NOT US_MODULE_LIBRARY_NAME AND NOT US_MODULE_EXECUTABLE) - set(US_MODULE_LIBRARY_NAME ${US_MODULE_NAME}) -endif() - -set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") -if(US_MODULE_EXECUTABLE) - string(REGEX MATCH ${_regex_validation} _valid_chars ${US_MODULE_NAME}) - if(NOT _valid_chars STREQUAL US_MODULE_NAME) - message(FATAL_ERROR "[Executable: ${US_MODULE_NAME}] MODULE_NAME contains illegal characters.") - endif() -else() - string(REGEX MATCH ${_regex_validation} _valid_chars ${US_MODULE_LIBRARY_NAME}) - if(NOT _valid_chars STREQUAL US_MODULE_LIBRARY_NAME) - message(FATAL_ERROR "[Module: ${US_MODULE_NAME}] LIBRARY_NAME \"${US_MODULE_LIBRARY_NAME}\" contains illegal characters.") - endif() -endif() - -# The call to MACRO_PARSE_ARGUMENTS always defines variables for the argument names. -# Check manually if AUTOLOAD_DIR was provided or not. -list(FIND ARGN AUTOLOAD_DIR _is_autoload_dir_defined) -if(_is_autoload_dir_defined EQUAL -1) - set(US_MODULE_AUTOLOAD_DIR ${US_MODULE_LIBRARY_NAME}) -endif() - -# Create variables of the ModuleInfo object, created in CMake/usModuleInit.cpp -set(US_MODULE_DEPENDS_STR "") -foreach(_dep ${US_MODULE_DEPENDS}) - set(US_MODULE_DEPENDS_STR "${US_MODULE_DEPENDS_STR} ${_dep}") -endforeach() - -if(US_MODULE_LIBRARY_NAME) - set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_LIBRARY_NAME}_init.cpp") -else() - set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_NAME}_init.cpp") -endif() - -configure_file(${CppMicroServices_SOURCE_DIR}/CMake/usModuleInit.cpp ${module_init_src_file} @ONLY) - -set(_src ${${src_var}} ${module_init_src_file}) -set(${src_var} ${_src} PARENT_SCOPE) - -endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usModuleInit.cpp b/Core/Code/CppMicroServices/CMake/usModuleInit.cpp deleted file mode 100644 index f9c9ddbe1a..0000000000 --- a/Core/Code/CppMicroServices/CMake/usModuleInit.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR("@US_MODULE_NAME@", "@US_MODULE_LIBRARY_NAME@", "@US_MODULE_AUTOLOAD_DIR@", "@US_MODULE_DEPENDS_STR@", "@US_MODULE_VERSION@") diff --git a/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake.in b/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake.in deleted file mode 100644 index 293031cb43..0000000000 --- a/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake.in +++ /dev/null @@ -1,19 +0,0 @@ -set(@PROJECT_NAME@_INCLUDE_DIRS @US_INCLUDE_DIRS@) -set(@PROJECT_NAME@_INTERNAL_INCLUDE_DIRS @US_INTERNAL_INCLUDE_DIRS@) -set(@PROJECT_NAME@_LIBRARIES @US_LINK_LIBRARIES@) -set(@PROJECT_NAME@_LIBRARY_DIRS @CMAKE_LIBRARY_OUTPUT_DIRECTORY@) - -set(@PROJECT_NAME@_SOURCES @US_SOURCES@) -set(@PROJECT_NAME@_PUBLIC_HEADERS @US_PUBLIC_HEADERS@) -set(@PROJECT_NAME@_PRIVATE_HEADERS @US_PRIVATE_HEADERS@) - -set(@PROJECT_NAME@_SOURCE_DIR @CMAKE_CURRENT_SOURCE_DIR@) - -set(CppMicroServices_RCC_EXECUTABLE_NAME @CppMicroServices_RCC_EXECUTABLE_NAME@) - -find_program(CppMicroServices_RCC_EXECUTABLE ${CppMicroServices_RCC_EXECUTABLE_NAME} - PATHS "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@" - PATH_SUFFIXES Release Debug RelWithDebInfo MinSizeRel) - -include(@CMAKE_CURRENT_SOURCE_DIR@/CMake/usFunctionGenerateModuleInit.cmake) -include(@CMAKE_CURRENT_SOURCE_DIR@/CMake/usFunctionEmbedResources.cmake) diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox deleted file mode 100644 index 8a7260e7be..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox +++ /dev/null @@ -1,85 +0,0 @@ - -/** - -\defgroup MicroServices Micro Services Classes - -\brief This category includes classes related to the C++ Micro Services component. - -The C++ Micro Services component provides a dynamic service registry based on the service layer -as specified in the OSGi R4.2 specifications. - -*/ - -/** - -\defgroup MicroServicesUtils Utility Classes - -\brief This category includes utility classes which can be used by others. - -*/ - -/** - -\page MicroServices_Examples Examples - -This is a list of available examples: - -- \subpage MicroServices_DictionaryService - -*/ - -/** - -\page MicroServices_Tutorials Tutorials - -This is a list of available tutorials: - -- \subpage MicroServices_TheModuleContext -- \subpage MicroServices_Resources -- \subpage MicroServices_EmulateSingleton -- \subpage MicroServices_AutoLoading -- \subpage MicroServices_StaticModules - -*/ - -/** - -\embmainpage{MicroServices_Overview} The C++ Micro Services - -The C++ Micro Services component provides a dynamic service registry based on the service layer -as specified in the OSGi R4.2 specifications. It enables users to realize a service oriented -approach within their software stack. The advantages include higher reuse of components, looser -coupling, better organization of responsibilities, cleaner API contracts, etc. - -\if us_standalone -\section MicroServices_Overview_BI Build Instructions - -How to build the C++ Micro Services library is explained in detail on the \ref BuildInstructions page. -\endif - -

Examples

- -\if us_standalone -Here is a list of \ref MicroServices_Examples "examples": -\else -Here is a list of \subpage MicroServices_Examples "examples": -\endif - -- \ref MicroServices_DictionaryService - -

Tutorials

- -The following list contains use cases and common patterns in the form of -\if us_standalone -\ref MicroServices_Tutorials "tutorials": -\else -\subpage MicroServices_Tutorials "tutorials": -\endif - -- \ref MicroServices_TheModuleContext -- \ref MicroServices_EmulateSingleton -- \ref MicroServices_AutoLoading -- \ref MicroServices_StaticModules - - -*/ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css b/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css deleted file mode 100644 index 8d4e9bba34..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css +++ /dev/null @@ -1,1141 +0,0 @@ -/* The standard CSS for doxygen */ - -/* -body, table, div, p, dl { - font-family: Lucida Grande, Verdana, Geneva, Arial, sans-serif; - font-size: 13px; - line-height: 1.3; -} -*/ - -/* @group Heading Levels */ - -h1 { - font-size: 150%; -} - -.title { - font-size: 150%; - font-weight: bold; - margin: 10px 2px; -} - -h2 { - font-size: 120%; -} - -h3 { - font-size: 100%; -} - -h1, h2, h3, h4, h5, h6 { - -webkit-transition: text-shadow 0.5s linear; - -moz-transition: text-shadow 0.5s linear; - -ms-transition: text-shadow 0.5s linear; - -o-transition: text-shadow 0.5s linear; - transition: text-shadow 0.5s linear; - margin-right: 15px; -} - -h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow { - text-shadow: 0 0 15px cyan; -} - -dt { - font-weight: bold; -} - -div.multicol { - -moz-column-gap: 1em; - -webkit-column-gap: 1em; - -moz-column-count: 3; - -webkit-column-count: 3; -} - -p.startli, p.startdd, p.starttd { - margin-top: 2px; -} - -p.endli { - margin-bottom: 0px; -} - -p.enddd { - margin-bottom: 4px; -} - -p.endtd { - margin-bottom: 2px; -} - -/* @end */ - -caption { - font-weight: bold; -} - -span.legend { - font-size: 70%; - text-align: center; -} - -h3.version { - font-size: 90%; - text-align: center; -} - -div.qindex, div.navtab{ - border: 1px solid #e6e6e6; - text-align: center; -} - -div.qindex, div.navpath { - width: 100%; - padding: 0 10px; -} - -div.navtab { - margin-right: 15px; -} - -/* @group Link Styling */ - -a { - font-weight: normal; - text-decoration: none; -} - -.contents a:visited { - color: #4665A2; -} - -a.qindex { - font-weight: bold; -} - -a.qindexHL { - font-weight: bold; - background-color: #9CAFD4; - color: #ffffff; - border: 1px double #869DCA; -} - -.contents a.qindexHL:visited { - color: #ffffff; -} - -a.el { - font-weight: bold; -} - -a.elRef { -} - -a.code, a.code:visited { - color: #4665A2; -} - -a.codeRef, a.codeRef:visited { - color: #4665A2; -} - -/* @end */ - -dl.el { - margin-left: -1cm; -} - -pre.fragment { - border-top-style: solid; - border-bottom-style: solid; - border-width: 1px 0 1px 0; - border-color: #e6e6e6; - border-radius: 0; - padding: 4px 6px; - margin: 4px 8px 4px 2px; - overflow: auto; - word-wrap: break-word; - font-size: 9pt; - line-height: 125%; -} - -div.fragment { - padding: 4px 6px; - margin: 4px 8px 4px 2px; - border-top-style: solid; - border-bottom-style: solid; - border-width: 1px 0 1px 0; - border-color: #e6e6e6; - background-color: #F5F5F5; -} - -div.line { - font-family: monospace, fixed; - font-size: 13px; - min-height: 13px; - line-height: 1.0; - text-wrap: unrestricted; - white-space: -moz-pre-wrap; /* Moz */ - white-space: -pre-wrap; /* Opera 4-6 */ - white-space: -o-pre-wrap; /* Opera 7 */ - white-space: pre-wrap; /* CSS3 */ - word-wrap: break-word; /* IE 5.5+ */ - text-indent: -53px; - padding-left: 53px; - padding-bottom: 0px; - margin: 0px; -} - -span.lineno { - padding-right: 4px; - text-align: right; - border-right: 2px solid #0F0; - background-color: #E8E8E8; - white-space: pre; -} -span.lineno a { - background-color: #D8D8D8; -} - -span.lineno a:hover { - background-color: #C8C8C8; -} - -div.ah { - background-color: #f6f6f6; - font-weight: bold; - margin-bottom: 3px; - margin-top: 3px; - padding: 0.2em; - border: solid thin #e6e6e6; - border-radius: 0.5em; - -webkit-border-radius: .5em; - -moz-border-radius: .5em; -} - -div.groupHeader { - margin-left: 16px; - margin-top: 12px; - font-weight: bold; -} - -div.groupText { - margin-left: 16px; - font-style: italic; -} - -div.contents { - margin-top: 10px; - margin-left: 12px; - margin-right: 8px; -} - -td.indexkey { - font-weight: bold; - margin: 2px 0px 2px 0; - padding: 2px 10px; - white-space: nowrap; - vertical-align: top; -} - -td.indexvalue { - padding: 2px 10px; - margin: 2px 0px; -} - -tr.memlist { - background-color: #EEF1F7; -} - -p.formulaDsp { - text-align: center; -} - -img.formulaDsp { - -} - -img.formulaInl { - vertical-align: middle; -} - -div.center { - text-align: center; - margin-top: 0px; - margin-bottom: 0px; - padding: 0px; -} - -div.center img { - border: 0px; -} - -address.footer { - text-align: right; - padding-right: 12px; -} - -img.footer { - border: 0px; - vertical-align: middle; -} - -/* @group Code Colorization */ - -span.keyword { - color: #008000 -} - -span.keywordtype { - color: #604020 -} - -span.keywordflow { - color: #e08000 -} - -span.comment { - color: #800000 -} - -span.preprocessor { - color: #806020 -} - -span.stringliteral { - color: #002080 -} - -span.charliteral { - color: #008080 -} - -span.vhdldigit { - color: #ff00ff -} - -span.vhdlchar { - color: #000000 -} - -span.vhdlkeyword { - color: #700070 -} - -span.vhdllogic { - color: #ff0000 -} - -blockquote { - background-color: #F7F8FB; - border-left: 2px solid #9CAFD4; - margin: 0 24px 0 4px; - padding: 0 12px 0 16px; -} - -/* @end */ - -/* -.search { - color: #003399; - font-weight: bold; -} - -form.search { - margin-bottom: 0px; - margin-top: 0px; -} - -input.search { - font-size: 75%; - color: #000080; - font-weight: normal; - background-color: #e8eef2; -} -*/ - -td.tiny { - font-size: 75%; -} - -.dirtab { - padding: 4px; - border-collapse: collapse; - border: 1px solid #A3B4D7; -} - -th.dirtab { - background: #EBEFF6; - font-weight: bold; -} - -hr { - height: 0px; - border: none; - border-top: 1px solid #e6e6e6; -} - -hr.footer { - height: 1px; -} - -/* @group Member Descriptions */ - -table.memberdecls { - border-spacing: 0px; - padding: 0px; -} - -.memberdecls td { - -webkit-transition-property: background-color, box-shadow; - -webkit-transition-duration: 0.5s; - -moz-transition-property: background-color, box-shadow; - -moz-transition-duration: 0.5s; - -ms-transition-property: background-color, box-shadow; - -ms-transition-duration: 0.5s; - -o-transition-property: background-color, box-shadow; - -o-transition-duration: 0.5s; - transition-property: background-color, box-shadow; - transition-duration: 0.5s; -} - -.memberdecls td.glow { - background-color: cyan; - box-shadow: 0 0 15px cyan; -} - -.mdescLeft, .mdescRight, -.memItemLeft, .memItemRight, -.memTemplItemLeft, .memTemplItemRight, .memTemplParams { - /*background-color: #F9FAFC;*/ - border: none; - margin: 4px; - padding: 1px 0 0 8px; -} - -.mdescLeft, .mdescRight { - padding: 0px 8px 4px 8px; - color: #555; -} - -/* -.memItemLeft, .memItemRight, .memTemplParams { - border-top: 1px solid #C4CFE5; -} -*/ - -.memItemLeft, .memTemplItemLeft { - white-space: nowrap; -} - -.memItemRight { - width: 100%; -} - -.memTemplParams { - color: #4665A2; - white-space: nowrap; -} - -/* @end */ - -/* @group Member Details */ - -/* Styles for detailed member documentation */ - -.memtemplate { - font-size: 80%; - color: #4665A2; - font-weight: normal; - margin-left: 9px; -} - -.memnav { - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; - margin: 2px; - margin-right: 15px; - padding: 2px; -} - -.mempage { - width: 100%; -} - -.memitem { - padding: 0; - margin-bottom: 10px; - margin-right: 5px; - -webkit-transition: box-shadow 0.5s linear; - -moz-transition: box-shadow 0.5s linear; - -ms-transition: box-shadow 0.5s linear; - -o-transition: box-shadow 0.5s linear; - transition: box-shadow 0.5s linear; -} - -.memitem.glow { - box-shadow: 0 0 15px cyan; -} - -.memname { - font-weight: bold; - margin-left: 6px; -} - -.memname td { - vertical-align: bottom; -} - -.memproto, dl.reflist dt { - border-top: 1px solid #e6e6e6; - border-left: 1px solid #e6e6e6; - border-right: 1px solid #e6e6e6; - padding: 6px 0px 6px 0px; - color: #253555; - font-weight: bold; - /* opera specific markup */ - border-top-right-radius: 8px; - border-top-left-radius: 8px; - /* firefox specific markup */ - -moz-border-radius-topright: 8px; - -moz-border-radius-topleft: 8px; - /* webkit specific markup */ - -webkit-border-top-right-radius: 8px; - -webkit-border-top-left-radius: 8px; - background-color: #f6f6f6; - -} - -.memdoc, dl.reflist dd { - border-bottom: 1px solid #e6e6e6; - border-left: 1px solid #e6e6e6; - border-right: 1px solid #e6e6e6; - padding: 2px 5px; - border-top-width: 0; - /* opera specific markup */ - border-bottom-left-radius: 8px; - border-bottom-right-radius: 8px; - /* firefox specific markup */ - -moz-border-radius-bottomleft: 8px; - -moz-border-radius-bottomright: 8px; - /* webkit specific markup */ - -webkit-border-bottom-left-radius: 8px; - -webkit-border-bottom-right-radius: 8px; -} - -dl.reflist dt { - padding: 5px; -} - -dl.reflist dd { - margin: 0px 0px 10px 0px; - padding: 5px; -} - -.paramkey { - text-align: right; -} - -.paramtype { - white-space: nowrap; -} - -.paramname { - color: #602020; - white-space: nowrap; -} -.paramname em { - font-style: normal; -} - -.params, .retval, .exception, .tparams { - margin-left: 0px; - padding-left: 0px; -} - -.params .paramname, .tparams .paramname, .retval .paramname { - font-weight: bold; - vertical-align: top; - padding-right: 10px; -} - -.params .paramtype { - font-style: italic; - vertical-align: top; -} - -.params .paramdir { - font-family: "courier new",courier,monospace; - vertical-align: top; -} - -table.mlabels { - border-spacing: 0px; -} - -td.mlabels-left { - width: 100%; - padding: 0px; -} - -td.mlabels-right { - vertical-align: bottom; - padding: 0px; - white-space: nowrap; -} - -span.mlabels { - margin-left: 8px; -} - -span.mlabel { - background-color: #728DC1; - border-top:1px solid #405C93; - border-left:1px solid #405C93; - border-right:1px solid #C4CFE5; - border-bottom:1px solid #C4CFE5; - text-shadow: none; - color: white; - margin-right: 4px; - padding: 2px 3px; - border-radius: 3px; - font-size: 7pt; - white-space: nowrap; -} - - - -/* @end */ - -/* these are for tree view when not used as main index */ - -div.directory { - margin: 10px 0px; - /*border-top: 1px solid #A8B8D9; - border-bottom: 1px solid #A8B8D9;*/ - width: 100%; -} - -.directory table { - border-collapse:collapse; -} - -.directory td { - margin: 0px; - padding: 0px; - vertical-align: baseline; -} - -.directory td.entry { - white-space: nowrap; - padding-right: 6px; -} - -.directory td.entry a { - outline:none; -} - -.directory td.desc { - width: 100%; - padding-left: 6px; - padding-right: 6px; - border-left: 1px solid rgba(0,0,0,0.05); -} - -.directory tr.even { - padding-left: 6px; - /*background-color: #F7F8FB;*/ -} - -.directory img { - vertical-align: -30%; -} - -.directory .levels { - white-space: nowrap; - width: 100%; - text-align: right; - font-size: 9pt; -} - -.directory .levels span { - cursor: pointer; - padding-left: 2px; - padding-right: 2px; - color: #3D578C; -} - -div.dynheader { - margin-top: 8px; -} - -address { - font-style: normal; - margin: 0; -} - -table.doxtable { - border-collapse:collapse; - margin-top: 4px; - margin-bottom: 4px; -} - -table.doxtable td, table.doxtable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -table.doxtable th { - background-color: #374F7F; - color: #FFFFFF; - font-size: 110%; - padding-bottom: 4px; - padding-top: 5px; -} - -table.fieldtable { - width: 100%; - margin-bottom: 10px; - border: 1px solid #A8B8D9; - border-spacing: 0px; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; - -webkit-box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); - box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); -} - -.fieldtable td, .fieldtable th { - padding: 3px 7px 2px; -} - -.fieldtable td.fieldtype, .fieldtable td.fieldname { - white-space: nowrap; - border-right: 1px solid #A8B8D9; - border-bottom: 1px solid #A8B8D9; - vertical-align: top; -} - -.fieldtable td.fielddoc { - border-bottom: 1px solid #A8B8D9; - width: 100%; -} - -.fieldtable tr:last-child td { - border-bottom: none; -} - -.fieldtable th { - background-image:url('nav_f.png'); - background-repeat:repeat-x; - background-color: #E2E8F2; - font-size: 90%; - color: #253555; - padding-bottom: 4px; - padding-top: 5px; - text-align:left; - -moz-border-radius-topleft: 4px; - -moz-border-radius-topright: 4px; - -webkit-border-top-left-radius: 4px; - -webkit-border-top-right-radius: 4px; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - border-bottom: 1px solid #A8B8D9; -} - - -.tabsearch { - top: 0px; - left: 10px; - height: 36px; - background-image: url('tab_b.png'); - z-index: 101; - overflow: hidden; - font-size: 13px; -} - -.navpath ul -{ - font-size: 11px; - overflow:hidden; - margin:0px; - padding:0px; -} - -.navpath li -{ - list-style-type:none; - float:left; - padding-left:10px; - padding-right:15px; -} - -.navpath li.navelem a -{ - height:22px; - display:block; - text-decoration: none; - outline: none; - color: #999; -} - -.navpath li.navelem a:hover -{ - text-decoration: underline; -} - -.navpath li.footer -{ - list-style-type:none; - float:right; - padding-left:10px; - padding-right:15px; - background-image:none; - background-repeat:no-repeat; - background-position:right; - color:#364D7C; - font-size: 8pt; -} - - -div.summary -{ - float: right; - font-size: 8pt; - padding-right: 5px; - width: 50%; - text-align: right; -} - -div.summary a -{ - white-space: nowrap; -} - -div.ingroups -{ - margin-left: 5px; - font-size: 8pt; - padding-left: 5px; - width: 50%; - text-align: left; -} - -div.ingroups a -{ - white-space: nowrap; -} - -div.header -{ - margin: 0px; - border-bottom: 1px solid #333333; -} - -div.headertitle -{ - padding: 0px 5px 0px 7px; -} - -dl -{ - padding: 0 0 0 10px; -} - -/* dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug */ -dl.section -{ - margin-left: 0px; - padding-left: 0px; -} - -dl.note -{ - padding-left: 3px; - border-left:4px solid; - border-color: #D0C000; -} - -dl.warning, dl.attention -{ - padding-left: 3px; - border-left:4px solid; - border-color: #FF0000; -} - -dl.pre, dl.post, dl.invariant -{ - padding-left: 3px; - border-left:4px solid; - border-color: #00D000; -} - -dl.deprecated -{ - padding-left: 3px; - border-left:4px solid; - border-color: #505050; -} - -dl.todo -{ - padding-left: 3px; - border-left:4px solid; - border-color: #00C0E0; -} - -dl.test -{ - padding-left: 3px; - border-left:4px solid; - border-color: #3030E0; -} - -dl.bug -{ - padding-left: 3px; - border-left:4px solid; - border-color: #C08050; -} - -dl.section dd { - margin-bottom: 6px; -} - - -#projectlogo -{ - text-align: center; - vertical-align: bottom; - border-collapse: separate; -} - -#projectlogo img -{ - border: 0px none; -} - -#projectname -{ - font: 300% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 2px 0px; -} - -#projectbrief -{ - font: 120% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#projectnumber -{ - font: 50% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#titlearea -{ - padding: 0px; - margin: 0px; - width: 100%; - border-bottom: 1px solid #5373B4; -} - -.image -{ - text-align: center; -} - -.dotgraph -{ - text-align: center; -} - -.mscgraph -{ - text-align: center; -} - -.caption -{ - font-weight: bold; -} - -div.zoom -{ - border: 1px solid #90A5CE; -} - -dl.citelist { - margin-bottom:50px; -} - -dl.citelist dt { - color:#334975; - float:left; - font-weight:bold; - margin-right:10px; - padding:5px; -} - -dl.citelist dd { - margin:2px 0; - padding:5px 0; -} - -div.toc { - padding: 14px 25px; - background-color: #F4F6FA; - border: 1px solid #D8DFEE; - border-radius: 7px 7px 7px 7px; - float: right; - height: auto; - margin: 0 20px 10px 10px; - width: 200px; -} - -div.toc li { - background: url("bdwn.png") no-repeat scroll 0 5px transparent; - font: 10px/1.2 Verdana,DejaVu Sans,Geneva,sans-serif; - margin-top: 5px; - padding-left: 10px; - padding-top: 2px; -} - -div.toc h3 { - font: bold 12px/1.2 Arial,FreeSans,sans-serif; - color: #4665A2; - border-bottom: 0 none; - margin: 0; -} - -div.toc ul { - list-style: none outside none; - border: medium none; - padding: 0px; -} - -div.toc li.level1 { - margin-left: 0px; -} - -div.toc li.level2 { - margin-left: 15px; -} - -div.toc li.level3 { - margin-left: 30px; -} - -div.toc li.level4 { - margin-left: 45px; -} - -.inherit_header { - font-weight: bold; - color: gray; - cursor: pointer; - -webkit-touch-callout: none; - -webkit-user-select: none; - -khtml-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.inherit_header td { - padding: 6px 0px 2px 5px; -} - -.inherit { - display: none; -} - -tr.heading h2 { - margin-top: 12px; - margin-bottom: 4px; -} - -@media print -{ - #top { display: none; } - #side-nav { display: none; } - #nav-path { display: none; } - body { overflow:visible; } - h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } - .summary { display: none; } - .memitem { page-break-inside: avoid; } - #doc-content - { - margin-left:0 !important; - height:auto !important; - width:auto !important; - overflow:inherit; - display:inline; - } -} - -code { - background-color: none; - border: none; - color: #333333; - padding: 1; -} - -.doxygen-header { - background-color: #F5F5F5; - margin: -20px -20px 20px; -} - -.tabs, .tabs2, .tabs3 { - width: 100%; - font-size: 16px; - position: relative; -} - -.tabs2 { - font-size: 14px; -} -.tabs3 { - font-size: 12px; -} - -.tablist { - margin: 0; - padding: 0; - display: table; -} - -.tablist li { - float: left; - display: table-cell; - list-style: none; -} - -.tablist a { - display: block; - padding: 10px 20px; - font-weight: bold; - color: #999999; - text-decoration: none; - outline: none; -} - -.tabs3 .tablist a { - padding: 0 10px; -} - -.tablist a:hover { - text-decoration: underline; -} - -.tablist li.current a { - color: #fff; - background-color: #bbb; -} - diff --git a/Core/Code/CppMicroServices/documentation/doxygen/examples/MicroServices_DictionaryService.md b/Core/Code/CppMicroServices/documentation/doxygen/examples/MicroServices_DictionaryService.md deleted file mode 100644 index 827280b91e..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/examples/MicroServices_DictionaryService.md +++ /dev/null @@ -1,29 +0,0 @@ -Implementing A Dictionary Service {#MicroServices_DictionaryService} -================================= - -This example demonstrates how to implement a service object. First, we must define the service interface -and then we define an implementation of that interface. In this particular example, we will create a -dictionary service that we can use to check if a word exists, which indicates if the word is spelled -correctly or not. - -We start by defining the dictionary interface (for example in a file called DictionaryService.h): - -\include uServices-dictionaryservice/DictionaryService.h - -The service interface is quite simple, with only one method that needs to be implemented. Notice that the -file does only contain the interface declaration and no actual code. - -In the following source code, the module uses its module context to register the dictionary service. -We implement the dictionary service as an inner class of the module activator class, but we could have also -put it in a separate file. Also note that there is no need to explicityl export any symbols from the module. - -\snippet uServices-dictionaryservice/main.cpp Activator - -Note that we do not need to unregister the service in the `Unload` method, because it will be done automatically -for us during static de-initialization of the module. - -In the last line, we "export" the module activator, assuming that it is contained in a module named -`DictionaryServiceModule`. We can get the highest ranking service implementation for the DictionaryService interface -by querying the service registry via the module context: - -\snippet uServices-dictionaryservice/main.cpp GetDictionaryService diff --git a/Core/Code/CppMicroServices/documentation/doxygen/header.html b/Core/Code/CppMicroServices/documentation/doxygen/header.html deleted file mode 100644 index 847964d749..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/header.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -layout: default -title: $title ---- - - - - - - - - - $treeview - $search - $mathjax - - - - - -
- diff --git a/Core/Code/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md b/Core/Code/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md deleted file mode 100644 index 949489d93b..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md +++ /dev/null @@ -1,83 +0,0 @@ -Build Instructions {#BuildInstructions} -================== - -The C++ Micro Services library provides [CMake][cmake] build scripts which allow the generation of -platform and IDE specific project files. - -The library should compile on many different platforms. Below is a list of tested compiler/OS combinations: - - - GCC 4.5 (Ubuntu 11.04 and MacOS X 10.6) - - Visual Studio 2008 and 2010 - - Clang 3.0 (Ubuntu 11.04 and MacOS X 10.6) - - -Prerequisites -------------- - -- [CMake][cmake] 2.8 (Visual Studio 2010 users should use the latest CMake version available) - - -Configuring the Build ---------------------- - -When building the C++ Micro Services library, you have a few configuration options at hand. - -### General build options - -- **US_BUILD_SHARED_LIBS** - Specify if the library should be build shared or static. See \ref MicroServices_StaticModules for detailed - information about static CppMicroServices modules. -- **US_BUILD_TESTING** - Build unit tests and code snippets. -- **US_ENABLE_AUTOLOADING_SUPPORT** - Enable auto-loading of modules located in special sup-directories. See \ref MicroServices_AutoLoading for - detailed information about this feature. -- **US_ENABLE_THREADING_SUPPORT** - Enable the use of synchronization primitives (atomics and pthread mutexes or Windows primitives) to make - the API thread-safe. If you are application is not multi-threaded, turn this option OFF to get maximum - performance. -- **US_USE_C++11 (advanced)** - Enable the usage of C++11 constructs -- **US_ENABLE_RESOURCE_COMPRESSION** - Enable compression of embedded resources. See \ref MicroServices_Resources for detailed information - about the resource system. - -### Customizing naming conventions - -- **US_NAMESPACE** - The default namespace is `us` but you may override this at will. -- **US_HEADER_PREFIX** - By default, all public headers have a "us" prefix. You may specify an arbitrary prefix to match your - naming conventions. - -The above options are mainly useful when embedding the C++ Micro Services source code in your own library and -you want to make it look like native source code. - -### Configure the service base class - -All service implementations must inherit from the same base class. The C++ Micro Services library provides -a trivial class called `us::Base` for that purpose. However, most applications already have a special base -class and you can configure the C++ Micro Services library to use that class. - -- **US_BASECLASS_NAME** - The fully-qualified name of the base class, e.g. `my::OwnBaseClass`. If you don't need support for service - factories (see below) and don't want to enable US_BUILD_TESTING, this is all you need. -- **US_ENABLE_SERVICE_FACTORY_SUPPORT (advanced)** - If you want support for service factories (they allow the customization of service objects for individual - modules, see OSGi Service Platform Core Specification Release 4, Version 4.3, Section 5.6), switch this - option to ON. If you also provided a custom US_BASECLASS_NAME, you need to set the US_BASECLASS_HEADER variable. -- **US_BASECLASS_HEADER (advanced)** - The name of the header file containing the declaration for the base class specified in US_BASECLASS_NAME, e.g. - `myOwnBaseClass.h`. You will also have to set US_BASECLASS_PACKAGE or US_BASECLASS_INCLUDE_DIRS and US_BASECLASS_LIBRARIES. -- **US_BASECLASS_PACKAGE (advanced)** - If your specified a custom base class from a library which can be found via a CMake `find_package` command, enter - the package name here. Most of the time, this will correctly set the values for US_BASECLASS_INCLUDE_DIRS, - US_BASECLASS_LIBRARIES, and US_BASECLASS_LIBRARY_DIRS. -- **US_BASECLASS_INCLUDE_DIRS (advanced)** - A list of include dirs needed to include the base class header file as specified in US_BASECLASS_HEADER. -- **US_BASECLASS_LIBRARIES (advanced)** - A list of libraries to link the C++ Micro Services library against for resolving symbols needed for a custom base class. -- **US_BASECLASS_LIBRARY_DIRS (advanced)** - A list of directories to look for the libraries specified in US_BASECLASS_LIBRARIES - -[cmake]: http://www.cmake.org diff --git a/Core/Code/CppMicroServices/documentation/snippets/CMakeLists.txt b/Core/Code/CppMicroServices/documentation/snippets/CMakeLists.txt deleted file mode 100644 index ce7de8a6b3..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ - -include_directories(${US_INCLUDE_DIRS}) -set(_link_libraries) -if(US_IS_EMBEDDED) - set(_link_libraries ${US_EMBEDDING_LIBRARY}) -else() - set(_link_libraries ${PROJECT_NAME}) -endif() - -usFunctionCompileSnippets("${CMAKE_CURRENT_SOURCE_DIR}" ${_link_libraries}) - diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake deleted file mode 100644 index 640356da1a..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake +++ /dev/null @@ -1,11 +0,0 @@ - -set(snippet_src_files - main.cpp - SingletonOne.cpp - SingletonTwo.cpp -) - -usFunctionGenerateModuleInit(snippet_src_files - NAME "uServices_singleton" - EXECUTABLE - ) diff --git a/Core/Code/CppMicroServices/src/module/usModuleInfo.cpp b/Core/Code/CppMicroServices/src/module/usModuleInfo.cpp deleted file mode 100644 index 669c333b67..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleInfo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usModuleInfo.h" - -US_BEGIN_NAMESPACE - -ModuleInfo::ModuleInfo(const std::string& name, const std::string& libName, - const std::string& autoLoadDir, const std::string& moduleDeps, - const std::string& version) - : name(name) - , libName(libName) - , moduleDeps(moduleDeps) - , version(version) - , autoLoadDir(autoLoadDir) - , id(0) - , activatorHook(NULL) -{} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceInterface.h b/Core/Code/CppMicroServices/src/service/usServiceInterface.h deleted file mode 100644 index abe6632457..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceInterface.h +++ /dev/null @@ -1,104 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICEINTERFACE_H -#define USSERVICEINTERFACE_H - -#include - -/** - * \ingroup MicroServices - * - * Returns a unique id for a given type. - * - * This template method is specialized in the macro - * #US_DECLARE_SERVICE_INTERFACE to return a unique id - * for each service interface. - * - * @tparam T The service interface type. - * @return A unique id for the service interface type T. - */ -template inline const char* us_service_interface_iid() -{ return 0; } - -template inline const char* us_service_impl_name(T* /*impl*/) -{ return "(unknown implementation)"; } - -#if defined(QT_DEBUG) || defined(QT_NO_DEBUG) -#include -#include US_BASECLASS_HEADER - -#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ - template<> inline const char* qobject_interface_iid<_service_interface_type *>() \ - { return _service_interface_id; } \ - template<> inline const char* us_service_interface_iid<_service_interface_type *>() \ - { return _service_interface_id; } \ - template<> inline _service_interface_type *qobject_cast<_service_interface_type *>(QObject *object) \ - { return dynamic_cast<_service_interface_type*>(reinterpret_cast((object ? object->qt_metacast(_service_interface_id) : 0))); } \ - template<> inline _service_interface_type *qobject_cast<_service_interface_type *>(const QObject *object) \ - { return dynamic_cast<_service_interface_type*>(reinterpret_cast((object ? const_cast(object)->qt_metacast(_service_interface_id) : 0))); } - -#else - -/** - * \ingroup MicroServices - * - * \brief Declare a CppMicroServices service interface. - * - * This macro associates the given identifier \e _service_interface_id (a string literal) to the - * interface class called _service_interface_type. The Identifier must be unique. For example: - * - * \code - * #include - * - * struct ISomeInterace { ... }; - * - * US_DECLARE_SERVICE_INTERFACE(ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") - * \endcode - * - * This macro is normally used right after the class definition for _service_interface_type, in a header file. - * - * If you want to use #US_DECLARE_SERVICE_INTERFACE with interface classes declared in a - * namespace then you have to make sure the #US_DECLARE_SERVICE_INTERFACE macro call is not - * inside a namespace though. For example: - * - * \code - * #include - * - * namespace Foo - * { - * struct ISomeInterface { ... }; - * } - * - * US_DECLARE_SERVICE_INTERFACE(Foo::ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") - * \endcode - * - * @param _service_interface_type The service interface type. - * @param _service_interface_id A string literal representing a globally unique identifier. - */ -#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ - template<> inline const char* us_service_interface_iid<_service_interface_type *>() \ - { return _service_interface_id; } \ - -#endif - -#endif // USSERVICEINTERFACE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.cpp b/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.cpp deleted file mode 100644 index 71bd9387a0..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include -#ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT -#include US_BASECLASS_HEADER -#endif - -#include "usServiceReferencePrivate.h" - -#include "usServiceFactory.h" -#include "usServiceException.h" -#include "usServiceRegistry_p.h" -#include "usServiceRegistrationPrivate.h" - -#include "usModule.h" -#include "usModulePrivate.h" - -#include - -US_BEGIN_NAMESPACE - -typedef ServiceRegistrationPrivate::MutexLocker MutexLocker; - -ServiceReferencePrivate::ServiceReferencePrivate(ServiceRegistrationPrivate* reg) - : ref(1), registration(reg) -{ - if(registration) registration->ref.Ref(); -} - -ServiceReferencePrivate::~ServiceReferencePrivate() -{ - if (registration && !registration->ref.Deref()) - delete registration; -} - -US_BASECLASS_NAME* ServiceReferencePrivate::GetService(Module* module) -{ - US_BASECLASS_NAME* s = 0; - { - MutexLocker lock(registration->propsLock); - if (registration->available) - { - int count = registration->dependents[module]; - if (count == 0) - { - registration->dependents[module] = 1; - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - const std::list& classes = - ref_any_cast >(registration->properties[ServiceConstants::OBJECTCLASS()]); - if (ServiceFactory* serviceFactory = dynamic_cast(registration->GetService())) - { - try - { - s = serviceFactory->GetService(module, ServiceRegistration(registration)); - } - catch (...) - { - US_WARN << "ServiceFactory threw an exception"; - return 0; - } - if (s == 0) { - US_WARN << "ServiceFactory produced null"; - return 0; - } - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) - { - if (!registration->module->coreCtx->services.CheckServiceClass(s, *i)) - { - US_WARN << "ServiceFactory produced an object " - "that did not implement: " << (*i); - return 0; - } - } - registration->serviceInstances.insert(std::make_pair(module, s)); - } - else - #endif - { - s = registration->GetService(); - } - } - else - { - registration->dependents.insert(std::make_pair(module, count + 1)); - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - if (dynamic_cast(registration->GetService())) - { - s = registration->serviceInstances[module]; - } - else - #endif - { - s = registration->GetService(); - } - } - } - } - return s; -} - -bool ServiceReferencePrivate::UngetService(Module* module, bool checkRefCounter) -{ - MutexLocker lock(registration->propsLock); - bool hadReferences = false; - bool removeService = false; - - int count= registration->dependents[module]; - if (count > 0) - { - hadReferences = true; - } - - if(checkRefCounter) - { - if (count > 1) - { - registration->dependents[module] = count - 1; - } - else if(count == 1) - { - removeService = true; - } - } - else - { - removeService = true; - } - - if (removeService) - { - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - US_BASECLASS_NAME* sfi = registration->serviceInstances[module]; - registration->serviceInstances.erase(module); - if (sfi != 0) - { - try - { - dynamic_cast( - registration->GetService())->UngetService(module, ServiceRegistration(registration), sfi); - } - catch (const std::exception& /*e*/) - { - US_WARN << "ServiceFactory threw an exception"; - } - } - #endif - registration->dependents.erase(module); - } - - return hadReferences; -} - -ServiceProperties ServiceReferencePrivate::GetProperties() const -{ - return registration->properties; -} - -Any ServiceReferencePrivate::GetProperty(const std::string& key, bool lock) const -{ - if (lock) - { - MutexLocker lock(registration->propsLock); - ServiceProperties::const_iterator iter = registration->properties.find(key); - if (iter != registration->properties.end()) - return iter->second; - } - else - { - ServiceProperties::const_iterator iter = registration->properties.find(key); - if (iter != registration->properties.end()) - return iter->second; - } - return Any(); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libAL2/CMakeLists.txt deleted file mode 100644 index bea2af0245..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL2/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ - -usFunctionCreateTestModuleWithAutoLoadDir(TestModuleAL2 "autoload_al2" usTestModuleAL2.cpp) - -add_subdirectory(libAL2_1) - diff --git a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp b/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp deleted file mode 100644 index 68be2b5a4c..0000000000 --- a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestUtilSharedLibrary.h" - -#include - -#include -#include -#include -#include - - -#if defined(US_PLATFORM_POSIX) - #include -#elif defined(US_PLATFORM_WINDOWS) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #include - #include -#else - #error Unsupported platform -#endif - - -US_BEGIN_NAMESPACE - -SharedLibraryHandle::SharedLibraryHandle() : m_Handle(0) {} - -SharedLibraryHandle::SharedLibraryHandle(const std::string& name) - : m_Name(name), m_Handle(0) -{} - -SharedLibraryHandle::~SharedLibraryHandle() -{} - -void SharedLibraryHandle::Load() -{ - Load(m_Name); -} - -void SharedLibraryHandle::Load(const std::string& name) -{ -#ifdef US_BUILD_SHARED_LIBS - if (m_Handle) throw std::logic_error(std::string("Library already loaded: ") + name); - std::string libPath = GetAbsolutePath(name); -#ifdef US_PLATFORM_POSIX - m_Handle = dlopen(libPath.c_str(), RTLD_LAZY | RTLD_GLOBAL); - if (!m_Handle) - { - const char* err = dlerror(); - throw std::runtime_error(err ? std::string(err) : libPath); - } -#else - m_Handle = LoadLibrary(libPath.c_str()); - if (!m_Handle) - { - std::string errMsg = "Loading "; - errMsg.append(libPath).append("failed with error: ").append(GetLastErrorStr()); - - throw std::runtime_error(errMsg); - } -#endif - -#endif - - m_Name = name; -} - -void SharedLibraryHandle::Unload() -{ -#ifdef US_BUILD_SHARED_LIBS - if (m_Handle) - { -#ifdef US_PLATFORM_POSIX - dlclose(m_Handle); -#else - FreeLibrary((HMODULE)m_Handle); -#endif - m_Handle = 0; - } -#endif -} - -std::string SharedLibraryHandle::GetAbsolutePath(const std::string& name) -{ - return GetLibraryPath() + "/" + Prefix() + name + Suffix(); -} - -std::string SharedLibraryHandle::GetAbsolutePath() -{ - return GetLibraryPath() + "/" + Prefix() + m_Name + Suffix(); -} - -std::string SharedLibraryHandle::GetLibraryPath() -{ -#ifdef US_PLATFORM_WINDOWS - return std::string(US_RUNTIME_OUTPUT_DIRECTORY); -#else - return std::string(US_LIBRARY_OUTPUT_DIRECTORY); -#endif -} - -std::string SharedLibraryHandle::Suffix() -{ -#ifdef US_PLATFORM_WINDOWS - return ".dll"; -#elif defined(US_PLATFORM_APPLE) - return ".dylib"; -#else - return ".so"; -#endif -} - -std::string SharedLibraryHandle::Prefix() -{ -#if defined(US_PLATFORM_POSIX) - return "lib"; -#else - return ""; -#endif -} - -US_END_NAMESPACE diff --git a/Core/CppMicroServices/.gitignore b/Core/CppMicroServices/.gitignore new file mode 100644 index 0000000000..cba86d0575 --- /dev/null +++ b/Core/CppMicroServices/.gitignore @@ -0,0 +1,6 @@ +*~ +*.o +*.so +CMakeLists.txt.user* +gh-pages +examples/makefile/main diff --git a/Core/CppMicroServices/.travis.yml b/Core/CppMicroServices/.travis.yml new file mode 100644 index 0000000000..75bc8fbe53 --- /dev/null +++ b/Core/CppMicroServices/.travis.yml @@ -0,0 +1,27 @@ +language: cpp +compiler: + - gcc + - clang +env: + - BUILD_CONFIGURATION=1 + - BUILD_CONFIGURATION=3 + - BUILD_CONFIGURATION=5 + - BUILD_CONFIGURATION=7 + - BUILD_CONFIGURATION=9 + - BUILD_CONFIGURATION=11 + - BUILD_CONFIGURATION=13 + - BUILD_CONFIGURATION=15 + - BUILD_CONFIGURATION=17 + - BUILD_CONFIGURATION=19 + - BUILD_CONFIGURATION=21 + - BUILD_CONFIGURATION=23 + - BUILD_CONFIGURATION=25 + - BUILD_CONFIGURATION=27 + - BUILD_CONFIGURATION=29 + - BUILD_CONFIGURATION=31 + +branches: + only: + - master + +script: ctest -S ./CMake/usCTestScript_travis.cmake diff --git a/Core/CppMicroServices/CMake/CMakePackageConfigHelpers.cmake b/Core/CppMicroServices/CMake/CMakePackageConfigHelpers.cmake new file mode 100644 index 0000000000..26f6cc264f --- /dev/null +++ b/Core/CppMicroServices/CMake/CMakePackageConfigHelpers.cmake @@ -0,0 +1,288 @@ +# - CONFIGURE_PACKAGE_CONFIG_FILE(), WRITE_BASIC_PACKAGE_VERSION_FILE() +# +# CONFIGURE_PACKAGE_CONFIG_FILE( INSTALL_DESTINATION +# [PATH_VARS ... ] +# [NO_SET_AND_CHECK_MACRO] +# [NO_CHECK_REQUIRED_COMPONENTS_MACRO]) +# +# CONFIGURE_PACKAGE_CONFIG_FILE() should be used instead of the plain +# configure_file() command when creating the Config.cmake or -config.cmake +# file for installing a project or library. It helps making the resulting package +# relocatable by avoiding hardcoded paths in the installed Config.cmake file. +# +# In a FooConfig.cmake file there may be code like this to make the +# install destinations know to the using project: +# set(FOO_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@" ) +# set(FOO_DATA_DIR "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" ) +# set(FOO_ICONS_DIR "@CMAKE_INSTALL_PREFIX@/share/icons" ) +# ...logic to determine installedPrefix from the own location... +# set(FOO_CONFIG_DIR "${installedPrefix}/@CONFIG_INSTALL_DIR@" ) +# All 4 options shown above are not sufficient, since the first 3 hardcode +# the absolute directory locations, and the 4th case works only if the logic +# to determine the installedPrefix is correct, and if CONFIG_INSTALL_DIR contains +# a relative path, which in general cannot be guaranteed. +# This has the effect that the resulting FooConfig.cmake file would work poorly +# under Windows and OSX, where users are used to choose the install location +# of a binary package at install time, independent from how CMAKE_INSTALL_PREFIX +# was set at build/cmake time. +# +# Using CONFIGURE_PACKAGE_CONFIG_FILE() helps. If used correctly, it makes the +# resulting FooConfig.cmake file relocatable. +# Usage: +# 1. write a FooConfig.cmake.in file as you are used to +# 2. insert a line containing only the string "@PACKAGE_INIT@" +# 3. instead of set(FOO_DIR "@SOME_INSTALL_DIR@"), use set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@") +# (this must be after the @PACKAGE_INIT@ line) +# 4. instead of using the normal configure_file(), use CONFIGURE_PACKAGE_CONFIG_FILE() +# +# The and arguments are the input and output file, the same way +# as in configure_file(). +# +# The given to INSTALL_DESTINATION must be the destination where the FooConfig.cmake +# file will be installed to. This can either be a relative or absolute path, both work. +# +# The variables to given as PATH_VARS are the variables which contain +# install destinations. For each of them the macro will create a helper variable +# PACKAGE_. These helper variables must be used +# in the FooConfig.cmake.in file for setting the installed location. They are calculated +# by CONFIGURE_PACKAGE_CONFIG_FILE() so that they are always relative to the +# installed location of the package. This works both for relative and also for absolute locations. +# For absolute locations it works only if the absolute location is a subdirectory +# of CMAKE_INSTALL_PREFIX. +# +# By default configure_package_config_file() also generates two helper macros, +# set_and_check() and check_required_components() into the FooConfig.cmake file. +# +# set_and_check() should be used instead of the normal set() +# command for setting directories and file locations. Additionally to setting the +# variable it also checks that the referenced file or directory actually exists +# and fails with a FATAL_ERROR otherwise. This makes sure that the created +# FooConfig.cmake file does not contain wrong references. +# When using the NO_SET_AND_CHECK_MACRO, this macro is not generated into the +# FooConfig.cmake file. +# +# check_required_components() should be called at the end of the +# FooConfig.cmake file if the package supports components. +# This macro checks whether all requested, non-optional components have been found, +# and if this is not the case, sets the Foo_FOUND variable to FALSE, so that the package +# is considered to be not found. +# It does that by testing the Foo__FOUND variables for all requested +# required components. +# When using the NO_CHECK_REQUIRED_COMPONENTS option, this macro is not generated +# into the FooConfig.cmake file. +# +# For an example see below the documentation for WRITE_BASIC_PACKAGE_VERSION_FILE(). +# +# +# WRITE_BASIC_PACKAGE_VERSION_FILE( filename VERSION major.minor.patch COMPATIBILITY (AnyNewerVersion|SameMajorVersion|ExactVersion) ) +# +# Writes a file for use as ConfigVersion.cmake file to . +# See the documentation of find_package() for details on this. +# filename is the output filename, it should be in the build tree. +# major.minor.patch is the version number of the project to be installed +# The COMPATIBILITY mode AnyNewerVersion means that the installed package version +# will be considered compatible if it is newer or exactly the same as the requested version. +# This mode should be used for packages which are fully backward compatible, +# also across major versions. +# If SameMajorVersion is used instead, then the behaviour differs from AnyNewerVersion +# in that the major version number must be the same as requested, e.g. version 2.0 will +# not be considered compatible if 1.0 is requested. +# This mode should be used for packages which guarantee backward compatibility within the +# same major version. +# If ExactVersion is used, then the package is only considered compatible if the requested +# version matches exactly its own version number (not considering the tweak version). +# For example, version 1.2.3 of a package is only considered compatible to requested version 1.2.3. +# This mode is for packages without compatibility guarantees. +# If your project has more elaborated version matching rules, you will need to write your +# own custom ConfigVersion.cmake file instead of using this macro. +# +# Internally, this macro executes configure_file() to create the resulting +# version file. Depending on the COMPATIBLITY, either the file +# BasicConfigVersion-SameMajorVersion.cmake.in or BasicConfigVersion-AnyNewerVersion.cmake.in +# is used. Please note that these two files are internal to CMake and you should +# not call configure_file() on them yourself, but they can be used as starting +# point to create more sophisticted custom ConfigVersion.cmake files. +# +# +# Example using both configure_package_config_file() and write_basic_package_version_file(): +# CMakeLists.txt: +# set(INCLUDE_INSTALL_DIR include/ ... CACHE ) +# set(LIB_INSTALL_DIR lib/ ... CACHE ) +# set(SYSCONFIG_INSTALL_DIR etc/foo/ ... CACHE ) +# ... +# include(CMakePackageConfigHelpers) +# configure_package_config_file(FooConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake +# INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake +# PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR) +# write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake +# VERSION 1.2.3 +# COMPATIBILITY SameMajorVersion ) +# install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake +# DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake ) +# +# With a FooConfig.cmake.in: +# set(FOO_VERSION x.y.z) +# ... +# @PACKAGE_INIT@ +# ... +# set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@") +# set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@") +# +# check_required_components(Foo) + +#============================================================================= +# Copyright 2012 Alexander Neundorf +# +# CMake - Cross Platform Makefile Generator +# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of Kitware, Inc., the Insight Software Consortium, +# nor the names of their contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ +# +# The above copyright and license notice applies to distributions of +# CMake in source and binary form. Some source files contain additional +# notices of original copyright by their contributors; see each source +# for details. Third-party software packages supplied with CMake under +# compatible licenses provide their own copyright notices documented in +# corresponding subdirectories. +# +#------------------------------------------------------------------------------ +# +# CMake was initially developed by Kitware with the following sponsorship: +# +# * National Library of Medicine at the National Institutes of Health +# as part of the Insight Segmentation and Registration Toolkit (ITK). +# +# * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel +# Visualization Initiative. +# +# * National Alliance for Medical Image Computing (NAMIC) is funded by the +# National Institutes of Health through the NIH Roadmap for Medical Research, +# Grant U54 EB005149. +# +# * Kitware, Inc. +#============================================================================= + +include(CMakeParseArguments) + +function(CONFIGURE_PACKAGE_CONFIG_FILE _inputFile _outputFile) + set(options NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO) + set(oneValueArgs INSTALL_DESTINATION ) + set(multiValueArgs PATH_VARS ) + + cmake_parse_arguments(CCF "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + if(CCF_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to CONFIGURE_PACKAGE_CONFIG_FILE(): \"${CCF_UNPARSED_ARGUMENTS}\"") + endif() + + if(NOT CCF_INSTALL_DESTINATION) + message(FATAL_ERROR "No INSTALL_DESTINATION given to CONFIGURE_PACKAGE_CONFIG_FILE()") + endif() + + if(IS_ABSOLUTE "${CCF_INSTALL_DESTINATION}") + set(absInstallDir "${CCF_INSTALL_DESTINATION}") + else() + set(absInstallDir "${CMAKE_INSTALL_PREFIX}/${CCF_INSTALL_DESTINATION}") + endif() + + file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${CMAKE_INSTALL_PREFIX}" ) + + foreach(var ${CCF_PATH_VARS}) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "Variable ${var} does not exist") + else() + if(IS_ABSOLUTE "${${var}}") + string(REPLACE "${CMAKE_INSTALL_PREFIX}" "\${PACKAGE_PREFIX_DIR}" + PACKAGE_${var} "${${var}}") + else() + set(PACKAGE_${var} "\${PACKAGE_PREFIX_DIR}/${${var}}") + endif() + endif() + endforeach() + + get_filename_component(inputFileName "${_inputFile}" NAME) + + set(PACKAGE_INIT " +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was ${inputFileName} ######## + +get_filename_component(PACKAGE_PREFIX_DIR \"\${CMAKE_CURRENT_LIST_DIR}/${PACKAGE_RELATIVE_PATH}\" ABSOLUTE) +") + + if("${absInstallDir}" MATCHES "^(/usr)?/lib(64)?/.+") + # Handle "/usr move" symlinks created by some Linux distros. + set(PACKAGE_INIT "${PACKAGE_INIT} +# Use original install prefix when loaded through a \"/usr move\" +# cross-prefix symbolic link such as /lib -> /usr/lib. +get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH) +get_filename_component(_realOrig \"${absInstallDir}\" REALPATH) +if(_realCurr STREQUAL _realOrig) + set(PACKAGE_PREFIX_DIR \"${CMAKE_INSTALL_PREFIX}\") +endif() +unset(_realOrig) +unset(_realCurr) +") + endif() + + if(NOT CCF_NO_SET_AND_CHECK_MACRO) + set(PACKAGE_INIT "${PACKAGE_INIT} +macro(set_and_check _var _file) + set(\${_var} \"\${_file}\") + if(NOT EXISTS \"\${_file}\") + message(FATAL_ERROR \"File or directory \${_file} referenced by variable \${_var} does not exist !\") + endif() +endmacro() +") + endif() + + + if(NOT CCF_NO_CHECK_REQUIRED_COMPONENTS_MACRO) + set(PACKAGE_INIT "${PACKAGE_INIT} +macro(check_required_components _NAME) + foreach(comp \${\${_NAME}_FIND_COMPONENTS}) + if(NOT \${_NAME}_\${comp}_FOUND) + if(\${_NAME}_FIND_REQUIRED_\${comp}) + set(\${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() +") + endif() + + set(PACKAGE_INIT "${PACKAGE_INIT} +####################################################################################") + + configure_file("${_inputFile}" "${_outputFile}" @ONLY) + +endfunction() diff --git a/Core/CppMicroServices/CMake/CMakeParseArguments.cmake b/Core/CppMicroServices/CMake/CMakeParseArguments.cmake new file mode 100644 index 0000000000..5e58023943 --- /dev/null +++ b/Core/CppMicroServices/CMake/CMakeParseArguments.cmake @@ -0,0 +1,186 @@ +# CMAKE_PARSE_ARGUMENTS( args...) +# +# CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions for +# parsing the arguments given to that macro or function. +# It processes the arguments and defines a set of variables which hold the +# values of the respective options. +# +# The argument contains all options for the respective macro, +# i.e. keywords which can be used when calling the macro without any value +# following, like e.g. the OPTIONAL keyword of the install() command. +# +# The argument contains all keywords for this macro +# which are followed by one value, like e.g. DESTINATION keyword of the +# install() command. +# +# The argument contains all keywords for this macro +# which can be followed by more than one value, like e.g. the TARGETS or +# FILES keywords of the install() command. +# +# When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the +# keywords listed in , and +# a variable composed of the given +# followed by "_" and the name of the respective keyword. +# These variables will then hold the respective value from the argument list. +# For the keywords this will be TRUE or FALSE. +# +# All remaining arguments are collected in a variable +# _UNPARSED_ARGUMENTS, this can be checked afterwards to see whether +# your macro was called with unrecognized parameters. +# +# As an example here a my_install() macro, which takes similar arguments as the +# real install() command: +# +# function(MY_INSTALL) +# set(options OPTIONAL FAST) +# set(oneValueArgs DESTINATION RENAME) +# set(multiValueArgs TARGETS CONFIGURATIONS) +# cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) +# ... +# +# Assume my_install() has been called like this: +# my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub) +# +# After the cmake_parse_arguments() call the macro will have set the following +# variables: +# MY_INSTALL_OPTIONAL = TRUE +# MY_INSTALL_FAST = FALSE (this option was not used when calling my_install() +# MY_INSTALL_DESTINATION = "bin" +# MY_INSTALL_RENAME = "" (was not used) +# MY_INSTALL_TARGETS = "foo;bar" +# MY_INSTALL_CONFIGURATIONS = "" (was not used) +# MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL" +# +# You can then continue and process these variables. +# +# Keywords terminate lists of values, e.g. if directly after a one_value_keyword +# another recognized keyword follows, this is interpreted as the beginning of +# the new option. +# E.g. my_install(TARGETS foo DESTINATION OPTIONAL) would result in +# MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION would +# be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor. + +#============================================================================= +# Copyright 2010 Alexander Neundorf +# +# CMake - Cross Platform Makefile Generator +# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of Kitware, Inc., the Insight Software Consortium, +# nor the names of their contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ +# +# The above copyright and license notice applies to distributions of +# CMake in source and binary form. Some source files contain additional +# notices of original copyright by their contributors; see each source +# for details. Third-party software packages supplied with CMake under +# compatible licenses provide their own copyright notices documented in +# corresponding subdirectories. +# +#------------------------------------------------------------------------------ +# +# CMake was initially developed by Kitware with the following sponsorship: +# +# * National Library of Medicine at the National Institutes of Health +# as part of the Insight Segmentation and Registration Toolkit (ITK). +# +# * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel +# Visualization Initiative. +# +# * National Alliance for Medical Image Computing (NAMIC) is funded by the +# National Institutes of Health through the NIH Roadmap for Medical Research, +# Grant U54 EB005149. +# +# * Kitware, Inc. +#============================================================================= + + +if(__CMAKE_PARSE_ARGUMENTS_INCLUDED) + return() +endif() +set(__CMAKE_PARSE_ARGUMENTS_INCLUDED TRUE) + + +function(CMAKE_PARSE_ARGUMENTS prefix _optionNames _singleArgNames _multiArgNames) + # first set all result variables to empty/FALSE + foreach(arg_name ${_singleArgNames} ${_multiArgNames}) + set(${prefix}_${arg_name}) + endforeach() + + foreach(option ${_optionNames}) + set(${prefix}_${option} FALSE) + endforeach() + + set(${prefix}_UNPARSED_ARGUMENTS) + + set(insideValues FALSE) + set(currentArgName) + + # now iterate over all arguments and fill the result variables + foreach(currentArg ${ARGN}) + list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword + list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword + list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword + + if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1) + if(insideValues) + if("${insideValues}" STREQUAL "SINGLE") + set(${prefix}_${currentArgName} ${currentArg}) + set(insideValues FALSE) + elseif("${insideValues}" STREQUAL "MULTI") + list(APPEND ${prefix}_${currentArgName} ${currentArg}) + endif() + else() + list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg}) + endif() + else() + if(NOT ${optionIndex} EQUAL -1) + set(${prefix}_${currentArg} TRUE) + set(insideValues FALSE) + elseif(NOT ${singleArgIndex} EQUAL -1) + set(currentArgName ${currentArg}) + set(${prefix}_${currentArgName}) + set(insideValues "SINGLE") + elseif(NOT ${multiArgIndex} EQUAL -1) + set(currentArgName ${currentArg}) + set(${prefix}_${currentArgName}) + set(insideValues "MULTI") + endif() + endif() + + endforeach() + + # propagate the result variables to the caller: + foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames}) + set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE) + endforeach() + set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE) + +endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usCTestScript.cmake b/Core/CppMicroServices/CMake/usCTestScript.cmake similarity index 97% rename from Core/Code/CppMicroServices/CMake/usCTestScript.cmake rename to Core/CppMicroServices/CMake/usCTestScript.cmake index 7feac62e8e..0a7f96535b 100644 --- a/Core/Code/CppMicroServices/CMake/usCTestScript.cmake +++ b/Core/CppMicroServices/CMake/usCTestScript.cmake @@ -1,131 +1,134 @@ macro(build_and_test) set(CTEST_SOURCE_DIRECTORY ${US_SOURCE_DIR}) set(CTEST_BINARY_DIRECTORY "${CTEST_DASHBOARD_ROOT}/${CTEST_PROJECT_NAME}_${CTEST_DASHBOARD_NAME}") #if(NOT CTEST_BUILD_NAME) # set(CTEST_BUILD_NAME "${CMAKE_SYSTEM}_${CTEST_COMPILER}_${CTEST_DASHBOARD_NAME}") #endif() ctest_empty_binary_directory(${CTEST_BINARY_DIRECTORY}) ctest_start("Experimental") if(NOT EXISTS "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt") file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" "${CTEST_INITIAL_CACHE}") endif() ctest_configure(RETURN_VALUE res) if (res) message(FATAL_ERROR "CMake configure error") endif() ctest_build(RETURN_VALUE res) if (res) message(FATAL_ERROR "CMake build error") endif() ctest_test(RETURN_VALUE res PARALLEL_LEVEL ${CTEST_PARALLEL_LEVEL}) if (res) message(FATAL_ERROR "CMake test error") endif() if(WITH_MEMCHECK AND CTEST_MEMORYCHECK_COMMAND) ctest_memcheck() endif() if(WITH_COVERAGE AND CTEST_COVERAGE_COMMAND) ctest_coverage() endif() #ctest_submit() endmacro() function(create_initial_cache var _shared _threading _sf _cxx11 _autoload) set(_initial_cache " US_BUILD_TESTING:BOOL=ON US_BUILD_SHARED_LIBS:BOOL=${_shared} US_ENABLE_THREADING_SUPPORT:BOOL=${_threading} US_ENABLE_SERVICE_FACTORY_SUPPORT:BOOL=${_sf} US_USE_C++11:BOOL=${_cxx11} US_ENABLE_AUTOLOADING_SUPPORT:BOOL=${_autoload} ") + if(_shared) + set(_initial_cache "${_initial_cache} US_BUILD_EXAMPLES:BOOL=ON + ") + endif() set(${var} ${_initial_cache} PARENT_SCOPE) if(_shared) set(CTEST_DASHBOARD_NAME "shared") else() set(CTEST_DASHBOARD_NAME "static") endif() if(_threading) set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-threading") endif() if(_sf) set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-servicefactory") endif() if(_cxx11) set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-cxx11") endif() if(_autoload) set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-autoloading") endif() set(CTEST_DASHBOARD_NAME ${CTEST_DASHBOARD_NAME} PARENT_SCOPE) endfunction() #========================================================= set(CTEST_PROJECT_NAME CppMicroServices) if(NOT CTEST_PARALLEL_LEVEL) set(CTEST_PARALLEL_LEVEL 1) endif() # SHARED THREADING SERVICE_FACTORY C++11 AUTOLOAD set(config0 0 0 0 0 0 ) set(config1 0 0 0 0 1 ) set(config2 0 0 0 1 0 ) set(config3 0 0 0 1 1 ) set(config4 0 0 1 0 0 ) set(config5 0 0 1 0 1 ) set(config6 0 0 1 1 0 ) set(config7 0 0 1 1 1 ) set(config8 0 1 0 0 0 ) set(config9 0 1 0 0 1 ) set(config10 0 1 0 1 0 ) set(config11 0 1 0 1 1 ) set(config12 0 1 1 0 0 ) set(config13 0 1 1 0 1 ) set(config14 0 1 1 1 0 ) set(config15 0 1 1 1 1 ) set(config16 1 0 0 0 0 ) set(config17 1 0 0 0 1 ) set(config18 1 0 0 1 0 ) set(config19 1 0 0 1 1 ) set(config20 1 0 1 0 0 ) set(config21 1 0 1 0 1 ) set(config22 1 0 1 1 0 ) set(config23 1 0 1 1 1 ) set(config24 1 1 0 0 0 ) set(config25 1 1 0 0 1 ) set(config26 1 1 0 1 0 ) set(config27 1 1 0 1 1 ) set(config28 1 1 1 0 0 ) set(config29 1 1 1 0 1 ) set(config30 1 1 1 1 0 ) set(config31 1 1 1 1 1 ) foreach(i ${US_BUILD_CONFIGURATION}) create_initial_cache(CTEST_INITIAL_CACHE ${config${i}}) message("Testing build configuration: ${CTEST_DASHBOARD_NAME}") build_and_test() endforeach() - diff --git a/Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake b/Core/CppMicroServices/CMake/usCTestScript_custom.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake rename to Core/CppMicroServices/CMake/usCTestScript_custom.cmake index 1a1faac564..cbdcba4727 100644 --- a/Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake +++ b/Core/CppMicroServices/CMake/usCTestScript_custom.cmake @@ -1,25 +1,24 @@ find_program(CTEST_COVERAGE_COMMAND NAMES gcov) find_program(CTEST_MEMORYCHECK_COMMAND NAMES valgrind) find_program(CTEST_GIT_COMMAND NAMES git) set(CTEST_SITE "bigeye") set(CTEST_DASHBOARD_ROOT "/tmp") #set(CTEST_COMPILER "gcc-4.5") set(CTEST_CMAKE_GENERATOR "Unix Makefiles") set(CTEST_BUILD_FLAGS "-j") set(CTEST_BUILD_CONFIGURATION Debug) set(CTEST_PARALLEL_LEVEL 4) set(US_TEST_SHARED 1) set(US_TEST_STATIC 1) set(US_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../") set(US_BUILD_CONFIGURATION ) foreach(i RANGE 31) list(APPEND US_BUILD_CONFIGURATION ${i}) endforeach() include(${US_SOURCE_DIR}/CMake/usCTestScript.cmake) - diff --git a/Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake b/Core/CppMicroServices/CMake/usCTestScript_travis.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake rename to Core/CppMicroServices/CMake/usCTestScript_travis.cmake index 1cd1030b3c..aea8b9e2ac 100644 --- a/Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake +++ b/Core/CppMicroServices/CMake/usCTestScript_travis.cmake @@ -1,18 +1,17 @@ find_program(CTEST_COVERAGE_COMMAND NAMES gcov) find_program(CTEST_MEMORYCHECK_COMMAND NAMES valgrind) find_program(CTEST_GIT_COMMAND NAMES git) set(CTEST_SITE "travis-ci") set(CTEST_DASHBOARD_ROOT "/tmp") #set(CTEST_COMPILER "gcc-4.5") set(CTEST_CMAKE_GENERATOR "Unix Makefiles") set(CTEST_BUILD_FLAGS "-j") set(CTEST_BUILD_CONFIGURATION Release) set(US_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../") set(US_BUILD_CONFIGURATION $ENV{BUILD_CONFIGURATION}) include(${US_SOURCE_DIR}/CMake/usCTestScript.cmake) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/CMake/usExecutableInit.cpp similarity index 90% copy from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp copy to Core/CppMicroServices/CMake/usExecutableInit.cpp index 9b0abf1b25..6e43c3d884 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/CMake/usExecutableInit.cpp @@ -1,31 +1,24 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#include - -US_BEGIN_NAMESPACE - -struct TestModuleAL_Dummy -{ -}; - -US_END_NAMESPACE +#include +US_INITIALIZE_EXECUTABLE("@US_EXECUTABLE_IDENTIFIER@") diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake b/Core/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake rename to Core/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake index 8e7e806576..4907ce5786 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake +++ b/Core/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake @@ -1,53 +1,52 @@ # # Helper macro allowing to check if the given flags are supported # by the underlying build tool # # If the flag(s) is/are supported, they will be appended to the string identified by RESULT_VAR # # Usage: # usFunctionCheckCompilerFlags(FLAGS_TO_CHECK VALID_FLAGS_VAR) # # Example: # # set(myflags) # usFunctionCheckCompilerFlags("-fprofile-arcs" myflags) # message(1-myflags:${myflags}) # usFunctionCheckCompilerFlags("-fauto-bugfix" myflags) # message(2-myflags:${myflags}) # usFunctionCheckCompilerFlags("-Wall" myflags) # message(1-myflags:${myflags}) # # The output will be: # 1-myflags: -fprofile-arcs # 2-myflags: -fprofile-arcs # 3-myflags: -fprofile-arcs -Wall include(TestCXXAcceptsFlag) function(usFunctionCheckCompilerFlags CXX_FLAG_TO_TEST RESULT_VAR) if(CXX_FLAG_TO_TEST STREQUAL "") message(FATAL_ERROR "CXX_FLAG_TO_TEST shouldn't be empty") endif() set(_test_flag ${CXX_FLAG_TO_TEST}) CHECK_CXX_ACCEPTS_FLAG("-Werror=unknown-warning-option" HAS_FLAG_unknown-warning-option) if(HAS_FLAG_unknown-warning-option) set(_test_flag "-Werror=unknown-warning-option ${CXX_FLAG_TO_TEST}") endif() # Internally, the macro CMAKE_CXX_ACCEPTS_FLAG calls TRY_COMPILE. To avoid # the cost of compiling the test each time the project is configured, the variable set by # the macro is added to the cache so that following invocation of the macro with # the same variable name skip the compilation step. # For that same reason, usFunctionCheckCompilerFlags function appends a unique suffix to # the HAS_FLAG variable. This suffix is created using a 'clean version' of the flag to test. string(REGEX REPLACE "-\\s\\$\\+\\*\\{\\}\\(\\)\\#" "" suffix ${CXX_FLAG_TO_TEST}) CHECK_CXX_ACCEPTS_FLAG(${_test_flag} HAS_FLAG_${suffix}) if(HAS_FLAG_${suffix}) set(${RESULT_VAR} "${${RESULT_VAR}} ${CXX_FLAG_TO_TEST}" PARENT_SCOPE) endif() endfunction() - diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake b/Core/CppMicroServices/CMake/usFunctionCompileSnippets.cmake similarity index 94% rename from Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake rename to Core/CppMicroServices/CMake/usFunctionCompileSnippets.cmake index 962e2e9c37..47f67f503f 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake +++ b/Core/CppMicroServices/CMake/usFunctionCompileSnippets.cmake @@ -1,49 +1,48 @@ function(usFunctionCompileSnippets snippet_path) # get all files called "main.cpp" file(GLOB_RECURSE main_cpp_list "${snippet_path}/main.cpp") foreach(main_cpp_file ${main_cpp_list}) # get the directory containing the main.cpp file get_filename_component(main_cpp_dir "${main_cpp_file}" PATH) set(snippet_src_files ) # If there exists a "files.cmake" file in the snippet directory, # include it and assume it sets the variable "snippet_src_files" # to a list of source files for the snippet. if(EXISTS "${main_cpp_dir}/files.cmake") include("${main_cpp_dir}/files.cmake") set(_tmp_src_files ${snippet_src_files}) set(snippet_src_files ) foreach(_src_file ${_tmp_src_files}) if(IS_ABSOLUTE ${_src_file}) list(APPEND snippet_src_files ${_src_file}) else() list(APPEND snippet_src_files ${main_cpp_dir}/${_src_file}) endif() endforeach() else() # glob all files in the directory and add them to the snippet src list file(GLOB_RECURSE snippet_src_files "${main_cpp_dir}/*") endif() # Uset the top-level directory name as the executable name string(REPLACE "/" ";" main_cpp_dir_tokens "${main_cpp_dir}") list(GET main_cpp_dir_tokens -1 snippet_exec_name) set(snippet_target_name "Snippet-${snippet_exec_name}") + add_executable(${snippet_target_name} ${snippet_src_files}) - if(ARGN) - target_link_libraries(${snippet_target_name} ${ARGN} ${snippet_link_libraries}) - endif() + target_link_libraries(${snippet_target_name} ${US_LIBRARY_TARGET} ${snippet_link_libraries}) set_target_properties(${snippet_target_name} PROPERTIES LABELS Documentation RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/snippets" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/snippets" LIBRARY_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/snippets" OUTPUT_NAME ${snippet_exec_name} ) endforeach() endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake b/Core/CppMicroServices/CMake/usFunctionCreateTestModule.cmake similarity index 71% rename from Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake rename to Core/CppMicroServices/CMake/usFunctionCreateTestModule.cmake index 6d90dc0ae4..2ff602e560 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake +++ b/Core/CppMicroServices/CMake/usFunctionCreateTestModule.cmake @@ -1,51 +1,42 @@ macro(_us_create_test_module_helper) if(_res_files) usFunctionEmbedResources(_srcs LIBRARY_NAME ${name} ROOT_DIR ${_res_root} FILES ${_res_files}) endif() add_library(${name} ${_srcs}) if(NOT US_BUILD_SHARED_LIBS) set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS US_STATIC_MODULE) endif() if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64") get_property(_compile_flags TARGET ${name} PROPERTY COMPILE_FLAGS) set_property(TARGET ${name} PROPERTY COMPILE_FLAGS "${_compile_flags} -fPIC") endif() - target_link_libraries(${name} ${US_LINK_LIBRARIES}) - if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - target_link_libraries(${name} ${US_BASECLASS_LIBRARIES}) - endif() + target_link_libraries(${name} ${US_LIBRARY_TARGET} ${US_LINK_LIBRARIES}) set(_us_test_module_libs "${_us_test_module_libs};${name}" CACHE INTERNAL "" FORCE) endmacro() -function(usFunctionCreateTestModuleWithAutoLoadDir name autoload_dir) - set(_srcs ${ARGN}) - usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name} AUTOLOAD_DIR ${autoload_dir}) - _us_create_test_module_helper() -endfunction() - function(usFunctionCreateTestModule name) set(_srcs ${ARGN}) set(_res_files ) usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name}) _us_create_test_module_helper() endfunction() function(usFunctionCreateTestModuleWithResources name) - MACRO_PARSE_ARGUMENTS(US_TEST "SOURCES;RESOURCES;RESOURCES_ROOT" "" ${ARGN}) + cmake_parse_arguments(US_TEST "" "RESOURCES_ROOT" "SOURCES;RESOURCES" "" ${ARGN}) set(_srcs ${US_TEST_SOURCES}) set(_res_files ${US_TEST_RESOURCES}) if(US_TEST_RESOURCES_ROOT) set(_res_root ${US_TEST_RESOURCES_ROOT}) else() set(_res_root resources) endif() usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name}) _us_create_test_module_helper() endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake b/Core/CppMicroServices/CMake/usFunctionEmbedResources.cmake similarity index 98% rename from Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake rename to Core/CppMicroServices/CMake/usFunctionEmbedResources.cmake index c559177c5e..7452c168d1 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake +++ b/Core/CppMicroServices/CMake/usFunctionEmbedResources.cmake @@ -1,147 +1,148 @@ -#! Embed resources into a shared library or executable. +#! \ingroup MicroServicesCMake +#! \brief Embed resources into a shared library or executable. #! #! This CMake function uses an external command line program to generate a source #! file containing data from external resources such as text files or images. The path #! to the generated source file is appended to the \c src_var variable. #! #! Each module can call this function (at most once) to embed resources and make them #! available at runtime through the Module class. Resources can also be embedded into #! executables, using the EXECUTABLE_NAME argument instead of LIBRARY_NAME. #! #! Example usage: -#! \verbatim +#! \code{.cmake} #! set(module_srcs ) #! usFunctionEmbedResources(module_srcs #! LIBRARY_NAME "mylib" #! ROOT_DIR resources #! FILES config.properties logo.png #! ) -#! \endverbatim +#! \endcode #! #! \param LIBRARY_NAME (required if EXECUTABLE_NAME is empty) The library name of the module #! which will include the generated source file, without extension. #! \param EXECUTABLE_NAME (required if LIBRARY_NAME is empty) The name of the executable #! which will include the generated source file. #! \param COMPRESSION_LEVEL (optional) The zip compression level. Defaults to the default zip #! level. Level 0 disables compression. #! \param COMPRESSION_THRESHOLD (optional) The compression threshold ranging from 0 to 100 for #! actually compressing the resource data. The default threshold is 30, meaning a size #! reduction of 30 percent or better results in the resource data being compressed. #! \param ROOT_DIR (optional) The root path for all resources listed after the FILES argument. #! If no or a relative path is given, it is considered relativ to the current CMake source directory. #! \param FILES (optional) A list of resources (paths to external files in the file system) relative #! to the ROOT_DIR argument or the current CMake source directory if ROOT_DIR is empty. #! #! The ROOT_DIR and FILES arguments may be repeated any number of times to merge files from #! different root directories into the embedded resource tree (hence the relative file paths #! after the FILES argument must be unique). #! function(usFunctionEmbedResources src_var) set(prefix US_RESOURCE) set(arg_names LIBRARY_NAME EXECUTABLE_NAME COMPRESSION_LEVEL COMPRESSION_THRESHOLD ROOT_DIR FILES) foreach(arg_name ${arg_names}) set(${prefix}_${arg_name}) endforeach(arg_name) set(cmd_line_args ) set(absolute_res_files ) set(current_arg_name DEFAULT_ARGS) set(current_arg_list) set(current_root_dir ${CMAKE_CURRENT_SOURCE_DIR}) foreach(arg ${ARGN}) list(FIND arg_names "${arg}" is_arg_name) if(is_arg_name GREATER -1) set(${prefix}_${current_arg_name} ${current_arg_list}) set(current_arg_name "${arg}") set(current_arg_list) else() set(current_arg_list ${current_arg_list} "${arg}") if(current_arg_name STREQUAL "ROOT_DIR") set(current_root_dir "${arg}") if(NOT IS_ABSOLUTE ${current_root_dir}) set(current_root_dir "${CMAKE_CURRENT_SOURCE_DIR}/${current_root_dir}") endif() if(NOT IS_DIRECTORY ${current_root_dir}) message(SEND_ERROR "The ROOT_DIR argument is not a directory: ${current_root_dir}") endif() get_filename_component(current_root_dir "${current_root_dir}" REALPATH) file(TO_NATIVE_PATH "${current_root_dir}" current_root_dir_native) list(APPEND cmd_line_args -d "${current_root_dir_native}") elseif(current_arg_name STREQUAL "FILES") set(res_file "${current_root_dir}/${arg}") file(TO_NATIVE_PATH "${res_file}" res_file_native) if(IS_DIRECTORY ${res_file}) message(SEND_ERROR "A resource cannot be a directory: ${res_file_native}") endif() if(NOT EXISTS ${res_file}) message(SEND_ERROR "Resource does not exists: ${res_file_native}") endif() list(APPEND absolute_res_files ${res_file}) file(TO_NATIVE_PATH "${arg}" res_filename_native) list(APPEND cmd_line_args "${res_filename_native}") endif() endif(is_arg_name GREATER -1) endforeach(arg ${ARGN}) set(${prefix}_${current_arg_name} ${current_arg_list}) if(NOT src_var) message(SEND_ERROR "Output variable name not specified.") endif() if(US_RESOURCE_EXECUTABLE_NAME AND US_RESOURCE_LIBRARY_NAME) message(SEND_ERROR "Only one of LIBRARY_NAME or EXECUTABLE_NAME can be specified.") endif() if(NOT US_RESOURCE_LIBRARY_NAME AND NOT US_RESOURCE_EXECUTABLE_NAME) message(SEND_ERROR "LIBRARY_NAME or EXECUTABLE_NAME argument not specified.") endif() if(NOT US_RESOURCE_FILES) message(WARNING "No FILES argument given. Skipping resource processing.") return() endif() list(GET cmd_line_args 0 first_arg) if(NOT first_arg STREQUAL "-d") set(cmd_line_args -d "${CMAKE_CURRENT_SOURCE_DIR}" ${cmd_line_args}) endif() if(US_RESOURCE_COMPRESSION_LEVEL) set(cmd_line_args -c ${US_RESOURCE_COMPRESSION_LEVEL} ${cmd_line_args}) endif() if(US_RESOURCE_COMPRESSION_THRESHOLD) set(cmd_line_args -t ${US_RESOURCE_COMPRESSION_THRESHOLD} ${cmd_line_args}) endif() if(US_RESOURCE_LIBRARY_NAME) set(us_cpp_resource_file "${CMAKE_CURRENT_BINARY_DIR}/${US_RESOURCE_LIBRARY_NAME}_resources.cpp") set(us_lib_name ${US_RESOURCE_LIBRARY_NAME}) else() set(us_cpp_resource_file "${CMAKE_CURRENT_BINARY_DIR}/${US_RESOURCE_EXECUTABLE_NAME}_resources.cpp") set(us_lib_name "\"\"") endif() set(resource_compiler ${CppMicroServices_RCC_EXECUTABLE}) if(TARGET ${CppMicroServices_RCC_EXECUTABLE_NAME}) set(resource_compiler ${CppMicroServices_RCC_EXECUTABLE_NAME}) elseif(NOT resource_compiler) message(FATAL_ERROR "The CppMicroServices resource compiler was not found. Check the CppMicroServices_RCC_EXECUTABLE CMake variable.") endif() add_custom_command( OUTPUT ${us_cpp_resource_file} COMMAND ${resource_compiler} "${us_lib_name}" ${us_cpp_resource_file} ${cmd_line_args} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${absolute_res_files} ${resource_compiler} COMMENT "Generating embedded resource file ${us_cpp_resource_name}" ) set(${src_var} "${${src_var}};${us_cpp_resource_file}" PARENT_SCOPE) endfunction() diff --git a/Core/CppMicroServices/CMake/usFunctionGenerateExecutableInit.cmake b/Core/CppMicroServices/CMake/usFunctionGenerateExecutableInit.cmake new file mode 100644 index 0000000000..fc4030cf80 --- /dev/null +++ b/Core/CppMicroServices/CMake/usFunctionGenerateExecutableInit.cmake @@ -0,0 +1,43 @@ +#! \ingroup MicroServicesCMake +#! \brief Generate a source file which handles proper initialization of an executable. +#! +#! This CMake function will store the path to a generated source file in the +#! src_var variable, which should be compiled into an executable. Example usage: +#! +#! \code{.cmake} +#! set(executable_srcs ) +#! usFunctionGenerateExecutableInit(executable_srcs +#! IDENTIFIER "MyExecutable" +#! ) +#! add_executable(MyExecutable ${executable_srcs}) +#! \endcode +#! +#! \param src_var (required) The name of a list variable to which the path of the generated +#! source file will be appended. +#! \param IDENTIFIER (required) A valid C identifier for the executable. +#! +#! \see #usFunctionGenerateModuleInit +#! \see \ref MicroServices_AutoLoading +#! +function(usFunctionGenerateExecutableInit src_var) + + cmake_parse_arguments(US_EXECUTABLE "" "IDENTIFIER" "" ${ARGN}) + + # sanity checks + if(NOT US_EXECUTABLE_IDENTIFIER) + message(SEND_ERROR "IDENTIFIER argument is mandatory") + endif() + + set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") + string(REGEX MATCH ${_regex_validation} _valid_chars ${US_EXECUTABLE_IDENTIFIER}) + if(NOT _valid_chars STREQUAL US_EXECUTABLE_IDENTIFIER) + message(FATAL_ERROR "IDENTIFIER contains illegal characters.") + endif() + + set(exec_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_EXECUTABLE_IDENTIFIER}_init.cpp") + configure_file(${CppMicroServices_EXECUTABLE_INIT_TEMPLATE} ${exec_init_src_file} @ONLY) + + set(_src ${${src_var}} ${exec_init_src_file}) + set(${src_var} ${_src} PARENT_SCOPE) + +endfunction() diff --git a/Core/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake b/Core/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake new file mode 100644 index 0000000000..e02cb839cb --- /dev/null +++ b/Core/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake @@ -0,0 +1,54 @@ +#! \ingroup MicroServicesCMake +#! \brief Generate a source file which handles proper initialization of a module. +#! +#! This CMake function will store the path to a generated source file in the +#! src_var variable, which should be compiled into a module. Example usage: +#! +#! \code{.cmake} +#! set(module_srcs ) +#! usFunctionGenerateModuleInit(module_srcs +#! NAME "My Module" +#! LIBRARY_NAME "mylib" +#! ) +#! add_library(mylib ${module_srcs}) +#! \endcode +#! +#! \param src_var (required) The name of a list variable to which the path of the generated +#! source file will be appended. +#! \param NAME (required) A human-readable name for the module. +#! \param LIBRARY_NAME (optional) The name of the module, without extension. If empty, the +#! NAME argument will be used. +#! +#! \see #usFunctionGenerateExecutableInit +#! \see \ref MicroServices_AutoLoading +#! +function(usFunctionGenerateModuleInit src_var) + + cmake_parse_arguments(US_MODULE "EXECUTABLE" "NAME;LIBRARY_NAME" "" ${ARGN}) + + if(US_MODULE_EXECUTABLE) + message(SEND_ERROR "EXECUTABLE option no longer supported. Use usFunctionGenerateExecutableInit instead.") + endif() + + # sanity checks + if(NOT US_MODULE_NAME) + message(SEND_ERROR "NAME argument is mandatory") + endif() + + if(NOT US_MODULE_LIBRARY_NAME) + set(US_MODULE_LIBRARY_NAME ${US_MODULE_NAME}) + endif() + + set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") + string(REGEX MATCH ${_regex_validation} _valid_chars ${US_MODULE_LIBRARY_NAME}) + if(NOT _valid_chars STREQUAL US_MODULE_LIBRARY_NAME) + message(FATAL_ERROR "[Module: ${US_MODULE_NAME}] LIBRARY_NAME \"${US_MODULE_LIBRARY_NAME}\" contains illegal characters.") + endif() + + set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_LIBRARY_NAME}_init.cpp") + configure_file(${CppMicroServices_MODULE_INIT_TEMPLATE} ${module_init_src_file} @ONLY) + + set(_src ${${src_var}} ${module_init_src_file}) + set(${src_var} ${_src} PARENT_SCOPE) + +endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake b/Core/CppMicroServices/CMake/usFunctionGetGccVersion.cmake similarity index 99% rename from Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake rename to Core/CppMicroServices/CMake/usFunctionGetGccVersion.cmake index 053ef33b6b..022fa606cf 100644 --- a/Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake +++ b/Core/CppMicroServices/CMake/usFunctionGetGccVersion.cmake @@ -1,19 +1,18 @@ #! \brief Get the gcc version function(usFunctionGetGccVersion path_to_gcc output_var) if(CMAKE_COMPILER_IS_GNUCXX) execute_process( COMMAND ${path_to_gcc} -dumpversion RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_STRIP_TRAILING_WHITESPACE ) if(result) message(FATAL_ERROR "Failed to obtain compiler version running [${path_to_gcc} -dumpversion]: ${error}") endif() set(${output_var} ${output} PARENT_SCOPE) endif() endfunction() - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/CMake/usModuleInit.cpp similarity index 88% copy from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp copy to Core/CppMicroServices/CMake/usModuleInit.cpp index 9b0abf1b25..05678e8649 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/CMake/usModuleInit.cpp @@ -1,31 +1,24 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#include - -US_BEGIN_NAMESPACE - -struct TestModuleAL_Dummy -{ -}; - -US_END_NAMESPACE +#include +US_INITIALIZE_MODULE("@US_MODULE_NAME@", "@US_MODULE_LIBRARY_NAME@") diff --git a/Core/Code/CppMicroServices/CMake/usPublicHeaderWrapper.h.in b/Core/CppMicroServices/CMake/usPublicHeaderWrapper.h.in similarity index 100% rename from Core/Code/CppMicroServices/CMake/usPublicHeaderWrapper.h.in rename to Core/CppMicroServices/CMake/usPublicHeaderWrapper.h.in diff --git a/Core/Code/CppMicroServices/CMakeLists.txt b/Core/CppMicroServices/CMakeLists.txt similarity index 60% rename from Core/Code/CppMicroServices/CMakeLists.txt rename to Core/CppMicroServices/CMakeLists.txt index bed7726a9c..f15f788bbe 100644 --- a/Core/Code/CppMicroServices/CMakeLists.txt +++ b/Core/CppMicroServices/CMakeLists.txt @@ -1,357 +1,375 @@ project(CppMicroServices) -set(${PROJECT_NAME}_MAJOR_VERSION 0) +set(${PROJECT_NAME}_MAJOR_VERSION 1) set(${PROJECT_NAME}_MINOR_VERSION 99) set(${PROJECT_NAME}_PATCH_VERSION 0) set(${PROJECT_NAME}_VERSION ${${PROJECT_NAME}_MAJOR_VERSION}.${${PROJECT_NAME}_MINOR_VERSION}.${${PROJECT_NAME}_PATCH_VERSION}) cmake_minimum_required(VERSION 2.8) +cmake_policy(VERSION 2.8) +cmake_policy(SET CMP0017 NEW) #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- -include(MacroParseArguments) +include(CMakeParseArguments) +include(CMakePackageConfigHelpers) include(CheckCXXSourceCompiles) include(usFunctionCheckCompilerFlags) include(usFunctionEmbedResources) include(usFunctionGetGccVersion) include(usFunctionGenerateModuleInit) +include(usFunctionGenerateExecutableInit) #----------------------------------------------------------------------------- # Init output directories #----------------------------------------------------------------------------- set(US_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") set(US_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") set(US_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") foreach(_type ARCHIVE LIBRARY RUNTIME) if(NOT CMAKE_${_type}_OUTPUT_DIRECTORY) set(CMAKE_${_type}_OUTPUT_DIRECTORY ${US_${_type}_OUTPUT_DIRECTORY}) endif() endforeach() #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # CMake options #----------------------------------------------------------------------------- function(us_cache_var _var_name _var_default _var_type _var_help) set(_advanced 0) set(_force) foreach(_argn ${ARGN}) if(_argn STREQUAL ADVANCED) set(_advanced 1) elseif(_argn STREQUAL FORCE) set(_force FORCE) endif() endforeach() if(US_IS_EMBEDDED) if(NOT DEFINED ${_var_name} OR _force) set(${_var_name} ${_var_default} PARENT_SCOPE) endif() else() set(${_var_name} ${_var_default} CACHE ${_var_type} "${_var_help}" ${_force}) if(_advanced) mark_as_advanced(${_var_name}) endif() endif() endfunction() # Determine if we are being build inside a larger project if(NOT DEFINED US_IS_EMBEDDED) if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) set(US_IS_EMBEDDED 0) else() set(US_IS_EMBEDDED 1) set(CppMicroServices_EXPORTS 1) endif() endif() us_cache_var(US_ENABLE_AUTOLOADING_SUPPORT OFF BOOL "Enable module auto-loading support") -us_cache_var(US_ENABLE_SERVICE_FACTORY_SUPPORT ON BOOL "Enable Service Factory support" ADVANCED) us_cache_var(US_ENABLE_THREADING_SUPPORT OFF BOOL "Enable threading support") us_cache_var(US_ENABLE_DEBUG_OUTPUT OFF BOOL "Enable debug messages" ADVANCED) us_cache_var(US_ENABLE_RESOURCE_COMPRESSION ON BOOL "Enable resource compression" ADVANCED) us_cache_var(US_BUILD_SHARED_LIBS ON BOOL "Build shared libraries") us_cache_var(US_BUILD_TESTING OFF BOOL "Build tests") -if(MSVC10 OR MSVC11) +if(WIN32 AND NOT CYGWIN) + set(default_runtime_install_dir bin/) + set(default_library_install_dir bin/) + set(default_archive_install_dir lib/) + set(default_header_install_dir include/) + set(default_auxiliary_install_dir share/) +else() + set(default_runtime_install_dir bin/) + set(default_library_install_dir lib/${PROJECT_NAME}) + set(default_archive_install_dir lib/${PROJECT_NAME}) + set(default_header_install_dir include/${PROJECT_NAME}) + set(default_auxiliary_install_dir share/${PROJECT_NAME}) +endif() + +us_cache_var(RUNTIME_INSTALL_DIR ${default_runtime_install_dir} STRING "Relative install location for binaries" ADVANCED) +us_cache_var(LIBRARY_INSTALL_DIR ${default_library_install_dir} STRING "Relative install location for libraries" ADVANCED) +us_cache_var(ARCHIVE_INSTALL_DIR ${default_archive_install_dir} STRING "Relative install location for archives" ADVANCED) +us_cache_var(HEADER_INSTALL_DIR ${default_header_install_dir} STRING "Relative install location for headers" ADVANCED) +us_cache_var(AUXILIARY_INSTALL_DIR ${default_auxiliary_install_dir} STRING "Relative install location for auxiliary files" ADVANCED) + +if(MSVC10 OR MSVC11 OR MSVC12) # Visual Studio 2010 and newer have support for C++11 enabled by default set(US_USE_C++11 1) else() us_cache_var(US_USE_C++11 OFF BOOL "Enable the use of C++11 features" ADVANCED) endif() us_cache_var(US_NAMESPACE "us" STRING "The namespace for the C++ micro services entities") us_cache_var(US_HEADER_PREFIX "" STRING "The file name prefix for the public C++ micro services header files") -us_cache_var(US_BASECLASS_NAME "" STRING "The fully-qualified name of the base class") - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - us_cache_var(US_BASECLASS_PACKAGE "" STRING "The name of the package providing the base class definition" ADVANCED) - - set(bc_inc_d_doc "A list of include directories containing the header files for the base class") - us_cache_var(US_BASECLASS_INCLUDE_DIRS "" STRING "${bc_inc_d_doc}" ADVANCED) - - set(bc_lib_d_doc "A list of library directories for the base class") - us_cache_var(US_BASECLASS_LIBRARY_DIRS "" STRING "${bc_lib_d_doc}" ADVANCED) - - set(bc_lib_doc "A list of libraries needed for the base class") - us_cache_var(US_BASECLASS_LIBRARIES "" STRING "${bc_lib_doc}" ADVANCED) - - us_cache_var(US_BASECLASS_HEADER "" STRING "The name of the header file containing the base class declaration" ADVANCED) -endif() set(BUILD_SHARED_LIBS ${US_BUILD_SHARED_LIBS}) -# Sanity checks - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT OR US_BUILD_TESTING) - if(US_BASECLASS_PACKAGE) - find_package(${US_BASECLASS_PACKAGE} REQUIRED) - - # Try to get the include dirs - foreach(_suffix DIRECTORIES DIRS DIRECTORY DIR) - if(${US_BASECLASS_PACKAGE}_INCLUDE_${_suffix} AND NOT US_BASECLASS_INCLUDE_DIRS) - us_cache_var(US_BASECLASS_INCLUDE_DIRS "${${US_BASECLASS_PACKAGE}_INCLUDE_${_suffix}}" STRING "${bc_inc_d_doc}" FORCE) - break() - endif() - endforeach() - - # Try to get the library dirs - foreach(_suffix DIRECTORIES DIRS DIRECTORY DIR) - if(${US_BASECLASS_PACKAGE}_LIBRARY_${_suffix} AND NOT US_BASECLASS_LIBRARY_DIRS) - us_cache_var(US_BASECLASS_LIBRARY_DIRS "${${US_BASECLASS_PACKAGE}_LIBRARY_${_suffix}}" STRING "${bc_lib_d_doc}" FORCE) - break() - endif() - endforeach() - - # Try to get the libraries - foreach(_suffix LIBRARIES LIBS LIBRARY LIB) - if(${US_BASECLASS_PACKAGE}_${_suffix} AND NOT US_BASECLASS_LIBRARIES) - us_cache_var(US_BASECLASS_LIBRARIES "${${US_BASECLASS_PACKAGE}_${_suffix}}" STRING "${bc_lib_doc}" FORCE) - break() - endif() - endforeach() - - if(NOT US_BASECLASS_NAME) - message(FATAL_ERROR "US_BASECLASS_NAME not set") - elseif(NOT US_BASECLASS_HEADER) - message(FATAL_ERROR "US_BASECLASS_HEADER not set") - endif() - endif() - - if(US_ENABLE_SERVICE_FACTORY_SUPPORT AND US_BASECLASS_NAME AND NOT US_BASECLASS_HEADER) - message(FATAL_ERROR "US_ENABLE_SERVICE_FACTORY_SUPPORT requires a US_BASECLASS_HEADER value") - endif() -endif() - -set(_us_baseclass_default 0) -if(NOT US_BASECLASS_NAME) - message(WARNING "Using build in base class \"::${US_NAMESPACE}::Base\"") - set(_us_baseclass_default 1) - set(US_BASECLASS_NAME "${US_NAMESPACE}::Base") - set(US_BASECLASS_HEADER "usBase.h") -endif() - -if(US_BUILD_TESTING AND US_BASECLASS_NAME AND NOT US_BASECLASS_HEADER) - message(FATAL_ERROR "US_BUILD_TESTING requires a US_BASECLASS_HEADER value") -endif() - -set(US_BASECLASS_INCLUDE "#include <${US_BASECLASS_HEADER}>") - -string(REPLACE "::" ";" _bc_token "${US_BASECLASS_NAME}") -list(GET _bc_token -1 _bc_name) -list(REMOVE_AT _bc_token -1) - -set(US_BASECLASS_FORWARD_DECLARATION "") -foreach(_namespace_tok ${_bc_token}) - if(_namespace_tok) - set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}namespace ${_namespace_tok} { ") - endif() -endforeach() -set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}class ${_bc_name}; ") -foreach(_namespace_tok ${_bc_token}) - if(_namespace_tok) - set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}}") - endif() -endforeach() +set(${PROJECT_NAME}_MODULE_INIT_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/CMake/usModuleInit.cpp") +set(${PROJECT_NAME}_EXECUTABLE_INIT_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/CMake/usExecutableInit.cpp") #----------------------------------------------------------------------------- # US C/CXX Flags #----------------------------------------------------------------------------- -set(US_C_FLAGS "${COVERAGE_C_FLAGS} ${ADDITIONAL_C_FLAGS}") -set(US_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${ADDITIONAL_CXX_FLAGS}") +set(US_C_FLAGS) +set(US_C_FLAGS_RELEASE) +set(US_CXX_FLAGS) +set(US_CXX_FLAGS_RELEASE) # This is used as a preprocessor define set(US_USE_CXX11 ${US_USE_C++11}) # Set C++ compiler flags if(NOT MSVC) foreach(_cxxflag -Werror -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Woverloaded-virtual -Wnon-virtual-dtor -Wold-style-cast - -Wstrict-null-sentinel -Wsign-promo -fdiagnostics-show-option -D_FORTIFY_SOURCE=2) + -Wstrict-null-sentinel -Wsign-promo -fdiagnostics-show-option) usFunctionCheckCompilerFlags(${_cxxflag} US_CXX_FLAGS) endforeach() if(US_USE_C++11) usFunctionCheckCompilerFlags("-std=c++0x" US_CXX_FLAGS) endif() endif() if(CMAKE_COMPILER_IS_GNUCXX) usFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) + if(${GCC_VERSION} VERSION_LESS "4.0.0") + message(FATAL_ERROR "gcc version ${GCC_VERSION} not supported. Please use gcc >= 4.") + endif() # With older versions of gcc the flag -fstack-protector-all requires an extra dependency to libssp.so. # If the gcc version is lower than 4.4.0 and the build type is Release let's not include the flag. if(${GCC_VERSION} VERSION_GREATER "4.4.0" OR (CMAKE_BUILD_TYPE STREQUAL "Debug" AND ${GCC_VERSION} VERSION_LESS "4.4.0")) usFunctionCheckCompilerFlags("-fstack-protector-all" US_CXX_FLAGS) endif() if(MINGW) # suppress warnings about auto imported symbols set(US_CXX_FLAGS "-Wl,--enable-auto-import ${US_CXX_FLAGS}") # we need to define a Windows version set(US_CXX_FLAGS "-D_WIN32_WINNT=0x0500 ${US_CXX_FLAGS}") else() # Enable visibility support if(NOT ${GCC_VERSION} VERSION_LESS "4.5") usFunctionCheckCompilerFlags("-fvisibility=hidden -fvisibility-inlines-hidden" US_CXX_FLAGS) + else() + set(US_GCC_RTTI_WORKAROUND_NEEDED 1) endif() endif() + usFunctionCheckCompilerFlags("-O1 -D_FORTIFY_SOURCE=2" _fortify_source_flag) + if(_fortify_source_flag) + set(US_CXX_FLAGS_RELEASE "${US_CXX_FLAGS_RELEASE} -D_FORTIFY_SOURCE=2") + endif() + + elseif(MSVC) set(US_CXX_FLAGS "/MP /wd4996 ${US_CXX_FLAGS}") endif() if(NOT US_IS_EMBEDDED) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${US_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${US_CXX_FLAGS_RELEASE}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${US_C_FLAGS}") + set(CMAKE_C_FLAGS_REALEASE "${CMAKE_C_FLAGS_RELEASE} ${US_C_FLAGS_RELEASE}") endif() #----------------------------------------------------------------------------- # US Link Flags #----------------------------------------------------------------------------- set(US_LINK_FLAGS ) if(NOT MSVC) foreach(_linkflag -Wl,--no-undefined) set(_add_flag) usFunctionCheckCompilerFlags("${_linkflag}" _add_flag) if(_add_flag) set(US_LINK_FLAGS "${US_LINK_FLAGS} ${_linkflag}") endif() endforeach() endif() #----------------------------------------------------------------------------- # US Header Checks #----------------------------------------------------------------------------- include(CheckIncludeFile) CHECK_INCLUDE_FILE(stdint.h HAVE_STDINT) #----------------------------------------------------------------------------- # US include dirs and libraries #----------------------------------------------------------------------------- set(US_INCLUDE_DIRS ${PROJECT_BINARY_DIR}/include ) set(US_INTERNAL_INCLUDE_DIRS ${PROJECT_BINARY_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/util ${CMAKE_CURRENT_SOURCE_DIR}/src/service ${CMAKE_CURRENT_SOURCE_DIR}/src/module ) -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND US_INTERNAL_INCLUDE_DIRS ${US_BASECLASS_INCLUDE_DIRS}) -endif() - -# link libraries for third party libs +# link library for third party libs if(US_IS_EMBEDDED) - set(US_LINK_LIBRARIES ${US_EMBEDDING_LIBRARY}) + set(US_LIBRARY_TARGET ${US_EMBEDDING_LIBRARY}) else() - set(US_LINK_LIBRARIES ${PROJECT_NAME}) + set(US_LIBRARY_TARGET ${PROJECT_NAME}) endif() # link libraries for the CppMicroServices lib -set(_link_libraries ) +set(US_LINK_LIBRARIES ) if(UNIX) - list(APPEND _link_libraries dl) -endif() -list(APPEND US_LINK_LIBRARIES ${_link_libraries}) - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND US_LINK_LIBRARIES ${US_BASECLASS_LIBRARIES}) -endif() - -set(US_LINK_DIRS ) -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND US_LINK_DIRS ${US_BASECLASS_LIBRARY_DIRS}) + list(APPEND US_LINK_LIBRARIES dl) endif() #----------------------------------------------------------------------------- # Source directory #----------------------------------------------------------------------------- set(us_config_h_file "${PROJECT_BINARY_DIR}/include/usConfig.h") configure_file(usConfig.h.in ${us_config_h_file}) set(US_RCC_EXECUTABLE_NAME usResourceCompiler) set(CppMicroServices_RCC_EXECUTABLE_NAME ${US_RCC_EXECUTABLE_NAME}) add_subdirectory(tools) add_subdirectory(src) #----------------------------------------------------------------------------- # US testing #----------------------------------------------------------------------------- if(US_BUILD_TESTING) enable_testing() add_subdirectory(test) endif() #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- add_subdirectory(documentation) #----------------------------------------------------------------------------- -# Last configuration steps +# Last configuration and install steps #----------------------------------------------------------------------------- -configure_file(${PROJECT_NAME}Config.cmake.in ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake @ONLY) +if(NOT US_IS_EMBEDDED) + export(TARGETS ${PROJECT_NAME} ${US_RCC_EXECUTABLE_NAME} + FILE ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake) + install(EXPORT ${PROJECT_NAME}Targets + FILE ${PROJECT_NAME}Targets.cmake + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/) +endif() + +set(_install_cmake_scripts + ${${PROJECT_NAME}_MODULE_INIT_TEMPLATE} + ${${PROJECT_NAME}_EXECUTABLE_INIT_TEMPLATE} + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/CMakeParseArguments.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionGenerateModuleInit.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionGenerateExecutableInit.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/usFunctionEmbedResources.cmake + ) + +install(FILES ${_install_cmake_scripts} + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + ) + +# Configure CppMicroServicesConfig.cmake for the build tree + +set(PACKAGE_CONFIG_INCLUDE_DIR ${US_INCLUDE_DIRS}) +set(PACKAGE_CONFIG_RUNTIME_DIR ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +set(PACKAGE_CONFIG_CMAKE_DIR ${PROJECT_SOURCE_DIR}/CMake) +if(US_IS_EMBEDDED) + set(PACKAGE_EMBEDDED "if(@PROJECT_NAME@_IS_EMBEDDED) + set(@PROJECT_NAME@_INTERNAL_INCLUDE_DIRS @US_INTERNAL_INCLUDE_DIRS@) + set(@PROJECT_NAME@_SOURCES @US_SOURCES@) + set(@PROJECT_NAME@_PUBLIC_HEADERS @US_PUBLIC_HEADERS@) + set(@PROJECT_NAME@_PRIVATE_HEADERS @US_PRIVATE_HEADERS@) +endif()") +else() + set(PACKAGE_EMBEDDED ) +endif() + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in + ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + @ONLY + ) + +# Configure CppMicroServicesConfig.cmake for the install tree +set(CONFIG_INCLUDE_DIR ${HEADER_INSTALL_DIR}) +set(CONFIG_RUNTIME_DIR ${RUNTIME_INSTALL_DIR}) +set(CONFIG_CMAKE_DIR ${AUXILIARY_INSTALL_DIR}/CMake) +configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in + ${PROJECT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake + INSTALL_DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + PATH_VARS CONFIG_INCLUDE_DIR CONFIG_RUNTIME_DIR CONFIG_CMAKE_DIR + NO_SET_AND_CHECK_MACRO + NO_CHECK_REQUIRED_COMPONENTS_MACRO + ) + +# Version information +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}ConfigVersion.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + @ONLY + ) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + DESTINATION ${AUXILIARY_INSTALL_DIR}/CMake/ + COMPONENT sdk + ) + +#----------------------------------------------------------------------------- +# Build the examples +#----------------------------------------------------------------------------- + +option(US_BUILD_EXAMPLES "Build example projects" OFF) +if(US_BUILD_EXAMPLES) + if(NOT US_BUILD_SHARED_LIBS) + message(WARNING "Examples are not available if US_BUILD_SHARED_LIBS is OFF") + else() + set(CppMicroServices_DIR ${PROJECT_BINARY_DIR}) + add_subdirectory(examples) + endif() +endif() diff --git a/Core/Code/CppMicroServices/CTestConfig.cmake b/Core/CppMicroServices/CTestConfig.cmake similarity index 100% rename from Core/Code/CppMicroServices/CTestConfig.cmake rename to Core/CppMicroServices/CTestConfig.cmake diff --git a/Core/CppMicroServices/CppMicroServicesConfig.cmake.in b/Core/CppMicroServices/CppMicroServicesConfig.cmake.in new file mode 100644 index 0000000000..0a8e57d74d --- /dev/null +++ b/Core/CppMicroServices/CppMicroServicesConfig.cmake.in @@ -0,0 +1,36 @@ +@PACKAGE_INIT@ + +set(@PROJECT_NAME@_USE_CXX11 @US_USE_CXX11@) + +set(@PROJECT_NAME@_CXX_FLAGS "@US_CXX_FLAGS@") +set(@PROJECT_NAME@_CXX_FLAGS_RELEASE "@US_CXX_FLAGS_RELEASE@") +set(@PROJECT_NAME@_CXX_FLAGS_DEBUG "@US_CXX_FLAGS_DEBUG@") +set(@PROJECT_NAME@_C_FLAGS "@US_C_FLAGS@") +set(@PROJECT_NAME@_C_FLAGS_RELEASE "@US_C_FLAGS_RELEASE@") +set(@PROJECT_NAME@_C_FLAGS_DEBUG "@US_C_FLAGS_DEBUG@") + +set(@PROJECT_NAME@_INCLUDE_DIR @PACKAGE_CONFIG_INCLUDE_DIR@) + +set(@PROJECT_NAME@_RCC_EXECUTABLE_NAME @CppMicroServices_RCC_EXECUTABLE_NAME@) +set(@PROJECT_NAME@_MODULE_INIT_TEMPLATE @PACKAGE_CONFIG_CMAKE_DIR@/usModuleInit.cpp) +set(@PROJECT_NAME@_EXECUTABLE_INIT_TEMPLATE @PACKAGE_CONFIG_CMAKE_DIR@/usExecutableInit.cpp) + +set(@PROJECT_NAME@_INCLUDE_DIRS ${@PROJECT_NAME@_INCLUDE_DIR}) +set(@PROJECT_NAME@_LIBRARIES @US_LIBRARY_TARGET@) + +find_program(@PROJECT_NAME@_RCC_EXECUTABLE ${@PROJECT_NAME@_RCC_EXECUTABLE_NAME} + PATHS "@PACKAGE_CONFIG_RUNTIME_DIR@" + PATH_SUFFIXES Release Debug RelWithDebInfo MinSizeRel) +mark_as_advanced(@PROJECT_NAME@_RCC_EXECUTABLE) + +set(@PROJECT_NAME@_IS_EMBEDDED @US_IS_EMBEDDED@) +@PACKAGE_EMBEDDED@ + +if(NOT TARGET @PROJECT_NAME@ AND NOT @PROJECT_NAME@_IS_EMBEDDED) + include(${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake) +endif() + +include(@PACKAGE_CONFIG_CMAKE_DIR@/CMakeParseArguments.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionGenerateModuleInit.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionGenerateExecutableInit.cmake) +include(@PACKAGE_CONFIG_CMAKE_DIR@/usFunctionEmbedResources.cmake) diff --git a/Core/CppMicroServices/CppMicroServicesConfigVersion.cmake.in b/Core/CppMicroServices/CppMicroServicesConfigVersion.cmake.in new file mode 100644 index 0000000000..b5be35dea9 --- /dev/null +++ b/Core/CppMicroServices/CppMicroServicesConfigVersion.cmake.in @@ -0,0 +1,34 @@ +# The created file sets PACKAGE_VERSION_EXACT if the current version string and +# the requested version string are exactly the same and it sets +# PACKAGE_VERSION_COMPATIBLE if the current version major number == requested version major number +# and the current version minor number >= requested version minor number + +set(PACKAGE_VERSION_MAJOR @CppMicroServices_MAJOR_VERSION@) +set(PACKAGE_VERSION_MINOR @CppMicroServices_MINOR_VERSION@) +set(PACKAGE_VERSION_PATCH @CppMicroServices_PATCH_VERSION@) +set(PACKAGE_VERSION "@CppMicroServices_VERSION@") + +if(PACKAGE_VERSION VERSION_EQUAL PACKAGE_FIND_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) +else() + set(PACKAGE_VERSION_EXACT FALSE) + if(NOT PACKAGE_VERSION_MAJOR EQUAL PACKAGE_FIND_VERSION_MAJOR) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + elseif(PACKAGE_VERSION_MINOR LESS PACKAGE_FIND_VERSION_MINOR) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + endif() +endif() + +# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: +if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "@CMAKE_SIZEOF_VOID_P@" STREQUAL "") + return() +endif() + +# check that the installed version has the same 32/64bit-ness as the one which is currently searching: +if(NOT "${CMAKE_SIZEOF_VOID_P}" STREQUAL "@CMAKE_SIZEOF_VOID_P@") + math(EXPR installedBits "@CMAKE_SIZEOF_VOID_P@ * 8") + set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") + set(PACKAGE_VERSION_UNSUITABLE TRUE) +endif() diff --git a/Core/Code/CppMicroServices/LICENSE b/Core/CppMicroServices/LICENSE similarity index 100% rename from Core/Code/CppMicroServices/LICENSE rename to Core/CppMicroServices/LICENSE diff --git a/Core/Code/CppMicroServices/README.md b/Core/CppMicroServices/README.md similarity index 100% rename from Core/Code/CppMicroServices/README.md rename to Core/CppMicroServices/README.md diff --git a/Core/CppMicroServices/documentation/CMakeDoxygenFilter.cpp b/Core/CppMicroServices/documentation/CMakeDoxygenFilter.cpp new file mode 100644 index 0000000000..7aba552149 --- /dev/null +++ b/Core/CppMicroServices/documentation/CMakeDoxygenFilter.cpp @@ -0,0 +1,494 @@ +/*============================================================================= + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include + +#include + +//-------------------------------------- +// Utilitiy classes and functions +//-------------------------------------- + +struct ci_char_traits : public std::char_traits + // just inherit all the other functions + // that we don't need to override +{ + static bool eq(char c1, char c2) + { return toupper(c1) == toupper(c2); } + + static bool ne(char c1, char c2) + { return toupper(c1) != toupper(c2); } + + static bool lt(char c1, char c2) + { return toupper(c1) < toupper(c2); } + + static bool gt(char c1, char c2) + { return toupper(c1) > toupper(c2); } + + static int compare(const char* s1, const char* s2, std::size_t n) + { + while (n-- > 0) + { + if (lt(*s1, *s2)) return -1; + if (gt(*s1, *s2)) return 1; + ++s1; ++s2; + } + return 0; + } + + static const char* find(const char* s, int n, char a) + { + while (n-- > 0 && toupper(*s) != toupper(a)) + { + ++s; + } + return s; + } +}; + +typedef std::basic_string ci_string; + +//-------------------------------------- +// Lexer +//-------------------------------------- + +class CMakeLexer +{ +public: + + enum Token { + TOK_EOF = -1, + TOK_EOL = -2, + + // commands + TOK_MACRO = -3, TOK_ENDMACRO = -4, + TOK_FUNCTION = -5, TOK_ENDFUNCTION = -6, + TOK_DOXYGEN_COMMENT = -7, + TOK_SET = -8, + TOK_STRING_LITERAL = -100, + TOK_NUMBER_LITERAL = -102, + + // primary + TOK_IDENTIFIER = -200 + }; + + CMakeLexer(std::istream& is) + : _lastChar(' '), _is(is), _line(1), _col(1) + {} + + int getToken() + { + // skip whitespace + while (isspace(_lastChar) && _lastChar != '\r' && _lastChar != '\n') + { + _lastChar = getChar(); + } + + if (isalpha(_lastChar) || _lastChar == '_') + { + _identifier = _lastChar; + while (isalnum(_lastChar = getChar()) || _lastChar == '-' || _lastChar == '_') + { + _identifier += _lastChar; + } + + if (_identifier == "set") + return TOK_SET; + if (_identifier == "function") + return TOK_FUNCTION; + if (_identifier == "macro") + return TOK_MACRO; + if (_identifier == "endfunction") + return TOK_ENDFUNCTION; + if (_identifier == "endmacro") + return TOK_ENDMACRO; + return TOK_IDENTIFIER; + } + + if (isdigit(_lastChar)) + { + // very lax!! number detection + _identifier = _lastChar; + while (isalnum(_lastChar = getChar()) || _lastChar == '.' || _lastChar == ',') + { + _identifier += _lastChar; + } + return TOK_NUMBER_LITERAL; + } + + if (_lastChar == '#') + { + _lastChar = getChar(); + if (_lastChar == '!') + { + // found a doxygen comment marker + _identifier.clear(); + + _lastChar = getChar(); + while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r') + { + _identifier += _lastChar; + _lastChar = getChar(); + } + return TOK_DOXYGEN_COMMENT; + } + + // skip the comment + while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r') + { + _lastChar = getChar(); + } + } + + if (_lastChar == '"') + { + _lastChar = getChar(); + _identifier.clear(); + while (_lastChar != EOF && _lastChar != '"') + { + _identifier += _lastChar; + _lastChar = getChar(); + } + + // eat the closing " + _lastChar = getChar(); + return TOK_STRING_LITERAL; + } + + // don't eat the EOF + if (_lastChar == EOF) return TOK_EOF; + + // don't eat the EOL + if (_lastChar == '\r' || _lastChar == '\n') + { + if (_lastChar == '\r') _lastChar = getChar(); + if (_lastChar == '\n') _lastChar = getChar(); + return TOK_EOL; + } + + // return the character as its ascii value + int thisChar = _lastChar; + _lastChar = getChar(); + return thisChar; + } + + std::string getIdentifier() const + { + return std::string(_identifier.c_str()); + } + + int curLine() const + { return _line; } + + int curCol() const + { return _col; } + + int getChar() + { + int c = _is.get(); + updateLoc(c); + return c; + } + +private: + + void updateLoc(int c) + { + if (c == '\n' || c == '\r') + { + ++_line; + _col = 1; + } + else + { + ++_col; + } + } + + ci_string _identifier; + int _lastChar; + std::istream& _is; + + int _line; + int _col; +}; + +//-------------------------------------- +// Parser +//-------------------------------------- + +class CMakeParser +{ + +public: + + CMakeParser(std::istream& is, std::ostream& os) + : _is(is), _os(os), _lexer(is), _curToken(CMakeLexer::TOK_EOF), _lastToken(CMakeLexer::TOK_EOF) + { } + + int curToken() + { + return _curToken; + } + + int nextToken() + { + _lastToken = _curToken; + _curToken = _lexer.getToken(); + while (_curToken == CMakeLexer::TOK_EOL) + { + // Try to preserve lines in output to allow correct line number referencing by doxygen. + _os << std::endl; + _curToken = _lexer.getToken(); + } + return _curToken; + } + + void handleMacro() + { + if(!parseMacro()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleFunction() + { + if(!parseFunction()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleSet() + { + // SET(var ...) following a documentation block is assumed to be a variable declaration. + if (_lastToken != CMakeLexer::TOK_DOXYGEN_COMMENT) + { + // No comment block before + nextToken(); + } else if(!parseSet()) + { + // skip token for error recovery + nextToken(); + } + } + + void handleDoxygenComment() + { + _os << "///" << _lexer.getIdentifier(); + nextToken(); + } + + void handleTopLevelExpression() + { + // skip token + nextToken(); + } + +private: + + void printError(const char* str) + { + std::cerr << "Error: " << str << " (at line " << _lexer.curLine() << ", col " << _lexer.curCol() << ")"; + } + + bool parseMacro() + { + if (nextToken() != '(') + { + printError("Expected '(' after MACRO"); + return false; + } + + nextToken(); + std::string macroName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || macroName.empty()) + { + printError("Expected macro name"); + return false; + } + + _os << macroName << '('; + if (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << _lexer.getIdentifier(); + while (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << ", " << _lexer.getIdentifier(); + } + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ");"; + } + + // eat the ')' + nextToken(); + return true; + } + + bool parseSet() + { + if (nextToken() != '(') + { + printError("Expected '(' after SET"); + return false; + } + + nextToken(); + std::string variableName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || variableName.empty()) + { + printError("Expected variable name"); + return false; + } + + _os << "CMAKE_VARIABLE " << variableName; + + nextToken(); + while ((curToken() == CMakeLexer::TOK_IDENTIFIER) + || (curToken() == CMakeLexer::TOK_STRING_LITERAL) + || (curToken() == CMakeLexer::TOK_NUMBER_LITERAL)) + { + nextToken(); + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ";"; + } + + // eat the ')' + nextToken(); + return true; + } + + bool parseFunction() + { + if (nextToken() != '(') + { + printError("Expected '(' after FUNCTION"); + return false; + } + + nextToken(); + std::string funcName = _lexer.getIdentifier(); + if (curToken() != CMakeLexer::TOK_IDENTIFIER || funcName.empty()) + { + printError("Expected function name"); + return false; + } + + _os << funcName << '('; + if (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << _lexer.getIdentifier(); + while (nextToken() == CMakeLexer::TOK_IDENTIFIER) + { + _os << ", " << _lexer.getIdentifier(); + } + } + + if (curToken() != ')') + { + printError("Missing expected ')'"); + } + else + { + _os << ");"; + } + + // eat the ')' + nextToken(); + + return true; + } + + std::istream& _is; + std::ostream& _os; + CMakeLexer _lexer; + int _curToken; + int _lastToken; +}; + + +#define STRINGIFY(a) #a +#define DOUBLESTRINGIFY(a) STRINGIFY(a) + +int main(int argc, char** argv) +{ + assert(argc > 1); + + for (int i = 1; i < argc; ++i) + { + std::ifstream ifs(argv[i]); + std::ostream& os = std::cout; + + #ifdef USE_NAMESPACE + os << "namespace " << DOUBLESTRINGIFY(USE_NAMESPACE) << " {\n"; + #endif + + CMakeParser parser(ifs, os); + parser.nextToken(); + while (ifs.good()) + { + switch (parser.curToken()) + { + case CMakeLexer::TOK_EOF: + return ifs.get(); // eat EOF + case CMakeLexer::TOK_MACRO: + parser.handleMacro(); + break; + case CMakeLexer::TOK_FUNCTION: + parser.handleFunction(); + break; + case CMakeLexer::TOK_SET: + parser.handleSet(); + break; + case CMakeLexer::TOK_DOXYGEN_COMMENT: + parser.handleDoxygenComment(); + break; + default: + parser.handleTopLevelExpression(); + break; + } + } + + #ifdef USE_NAMESPACE + os << "}\n"; + #endif + } + + return EXIT_SUCCESS; +} diff --git a/Core/Code/CppMicroServices/documentation/CMakeLists.txt b/Core/CppMicroServices/documentation/CMakeLists.txt similarity index 61% rename from Core/Code/CppMicroServices/documentation/CMakeLists.txt rename to Core/CppMicroServices/documentation/CMakeLists.txt index 8ce17b7663..7aec333a00 100644 --- a/Core/Code/CppMicroServices/documentation/CMakeLists.txt +++ b/Core/CppMicroServices/documentation/CMakeLists.txt @@ -1,65 +1,84 @@ if(US_BUILD_TESTING) include(usFunctionCompileSnippets) # Compile source code snippets add_subdirectory(snippets) endif() -if(NOT US_IS_EMBEDDED) +if(NOT US_IS_EMBEDDED AND NOT US_NO_DOCUMENTATION) find_package(Doxygen) if(DOXYGEN_FOUND) - + option(US_DOCUMENTATION_FOR_WEBPAGE "Build Doxygen documentation for the webpage" OFF) set(US_DOXYGEN_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Doxygen output directory") mark_as_advanced(US_DOCUMENTATION_FOR_WEBPAGE US_DOXYGEN_OUTPUT_DIR) set(US_HAVE_DOT "NO") if(DOXYGEN_DOT_EXECUTABLE) set(US_HAVE_DOT "YES") endif() if(NOT DEFINED US_DOXYGEN_DOT_NUM_THREADS) set(US_DOXYGEN_DOT_NUM_THREADS 4) endif() - + # We are in standalone mode, so we generate a "mainpage" set(US_DOXYGEN_MAIN_PAGE_CMD "\\mainpage") set(US_DOXYGEN_ENABLED_SECTIONS "us_standalone") - + if(US_DOCUMENTATION_FOR_WEBPAGE) configure_file(doxygen/header.html ${CMAKE_CURRENT_BINARY_DIR}/header.html COPY_ONLY) set(US_DOXYGEN_HEADER header.html) configure_file(doxygen/footer.html ${CMAKE_CURRENT_BINARY_DIR}/footer.html COPY_ONLY) set(US_DOXYGEN_FOOTER footer.html) - configure_file(doxygen/doxygen.css - ${CMAKE_CURRENT_BINARY_DIR}/doxygen.css COPY_ONLY) - set(US_DOXYGEN_CSS doxygen.css) - + configure_file(doxygen/doxygen_extra.css + ${CMAKE_CURRENT_BINARY_DIR}/doxygen_extra.css COPY_ONLY) + set(US_DOXYGEN_EXTRA_CSS doxygen_extra.css) + set(US_DOXYGEN_OUTPUT_DIR ${PROJECT_SOURCE_DIR}/gh-pages) if(${PROJECT_NAME}_MINOR_VERSION EQUAL 99) set(US_DOXYGEN_HTML_OUTPUT "doc_latest") else() set(US_DOXYGEN_HTML_OUTPUT "doc_${${PROJECT_NAME}_MAJOR_VERSION}_${${PROJECT_NAME}_MINOR_VERSION}") endif() else() set(US_DOXYGEN_HEADER ) set(US_DOXYGEN_FOOTER ) set(US_DOXYGEN_CSS ) set(US_DOXYGEN_HTML_OUTPUT "html") endif() - + + # Compile a command line tool which transforms comments in CMake scripts into + # Doxygen parseable C code. + set(CMakeDoxygenFilter_EXECUTABLE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CMakeDoxygenFilter${CMAKE_EXECUTABLE_SUFFIX}") + try_compile(_result_var + "${CMAKE_CURRENT_BINARY_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/CMakeDoxygenFilter.cpp" + OUTPUT_VARIABLE _compile_output + COPY_FILE ${CMakeDoxygenFilter_EXECUTABLE} + ) + + if(NOT _result_var) + message(FATAL_ERROR "error: Faild to compile ${CMAKE_CURRENT_SOURCE_DIR}/CMakeDoxygenFilter.cpp (result: ${result_var})\n${_compile_output}") + endif() + configure_file(doxygen.conf.in ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf) add_custom_target(doc ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) + + install(CODE "execute_process(COMMAND \"${CMAKE_COMMAND}\" --build \"${PROJECT_BINARY_DIR}\" --target doc)") + + install(DIRECTORY ${US_DOXYGEN_OUTPUT_DIR}/${US_DOXYGEN_HTML_OUTPUT} + DESTINATION ${AUXILIARY_INSTALL_DIR}/doc/ + COMPONENT doc) endif() endif() - diff --git a/Core/Code/CppMicroServices/documentation/doxygen.conf.in b/Core/CppMicroServices/documentation/doxygen.conf.in similarity index 92% rename from Core/Code/CppMicroServices/documentation/doxygen.conf.in rename to Core/CppMicroServices/documentation/doxygen.conf.in index b3f88c4728..275eb52db2 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen.conf.in +++ b/Core/CppMicroServices/documentation/doxygen.conf.in @@ -1,1808 +1,1894 @@ -# Doxyfile 1.8.1 +# Doxyfile 1.8.3.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or sequence of words) that should # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. PROJECT_NAME = "C++ Micro Services" # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = @CppMicroServices_VERSION@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "A dynamic OSGi-like C++ service registry" # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = @US_DOXYGEN_OUTPUT_DIR@ # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the -# path to strip. +# path to strip. Note that you specify absolute paths here, but also +# relative paths, which will be relative from the directory where doxygen is +# started. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) -JAVADOC_AUTOBRIEF = NO +JAVADOC_AUTOBRIEF = YES # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 2 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = "FIXME=\par Fix Me's:\n" \ "embmainpage{1}=@US_DOXYGEN_MAIN_PAGE_CMD@" # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given extension. -# Doxygen has a built-in mapping, but you can override or extend it using this -# tag. The format is ext=language, where ext is a file extension, and language -# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, -# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions -# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, +# and language is one of the parsers supported by doxygen: IDL, Java, +# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, +# C++. For instance to make doxygen treat .inc files as Fortran files (default +# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note +# that for custom extensions you also need to set FILE_PATTERNS otherwise the +# files are not read by doxygen. EXTENSION_MAPPING = # If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all # comments according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you # can mix doxygen, HTML, and XML commands with Markdown formatting. # Disable only in case of backward compatibilities issues. MARKDOWN_SUPPORT = YES +# When enabled doxygen tries to link words that correspond to documented classes, +# or namespaces to their corresponding documentation. Such a link can be +# prevented in individual cases by by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. + +AUTOLINK_SUPPORT = YES + # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO -# For Microsoft's IDL there are propget and propput attributes to indicate getter -# and setter methods for a property. Setting this option to YES (the default) -# will make doxygen replace the get and set methods by a property in the -# documentation. This will only work if the methods are indeed getting or +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES (the +# default) will make doxygen replace the get and set methods by a property in +# the documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. -DISTRIBUTE_GROUP_DOC = NO +DISTRIBUTE_GROUP_DOC = YES # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given # their name and scope. Since this can be an expensive process and often the # same symbol appear multiple times in the code, doxygen keeps a cache of # pre-resolved symbols. If the cache is too small doxygen will become slower. # If the cache is too large, memory is wasted. The cache size is given by this # formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal scope will be included in the documentation. +# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal +# scope will be included in the documentation. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = NO # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = YES # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = YES # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if sectionname ... \endif. +# documentation sections, marked by \if section-label ... \endif +# and \cond section-label ... \endcond blocks. ENABLED_SECTIONS = @US_DOXYGEN_ENABLED_SECTIONS@ # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 0 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = NO # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. The create the layout file +# output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this -# feature you need bibtex and perl available in the search path. +# feature you need bibtex and perl available in the search path. Do not use +# file names with spaces, bibtex cannot handle them. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @PROJECT_SOURCE_DIR@ \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionEmbedResources.cmake \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionGenerateModuleInit.cmake \ + @PROJECT_SOURCE_DIR@/CMake/usFunctionGenerateExecutableInit.cmake \ @PROJECT_BINARY_DIR@/include/usConfig.h # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = *.h \ *.dox \ *.md # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = @PROJECT_SOURCE_DIR@/README.md \ @PROJECT_SOURCE_DIR@/documentation/snippets/ \ + @PROJECT_SOURCE_DIR@/examples/ \ @PROJECT_SOURCE_DIR@/test/ \ - @PROJECT_SOURCE_DIR@/gh-pages \ + @PROJECT_SOURCE_DIR@/gh-pages/ \ @PROJECT_SOURCE_DIR@/.git/ # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = */.git/* \ *_p.h \ *Private.* # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test -EXCLUDE_SYMBOLS = us US_NAMESPACE +EXCLUDE_SYMBOLS = us \ + US_NAMESPACE \ + *Private* \ + ModuleInfo \ + ServiceObjectsBase* \ + TrackedService* # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). -EXAMPLE_PATH = @PROJECT_SOURCE_DIR@/documentation/snippets/ +EXAMPLE_PATH = @PROJECT_SOURCE_DIR@/documentation/snippets/ \ + @PROJECT_SOURCE_DIR@/examples/ # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = YES # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. -FILTER_PATTERNS = +FILTER_PATTERNS = *.cmake=@CMakeDoxygenFilter_EXECUTABLE@ # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = +# If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page (index.html). +# This can be useful if you have a project on for instance GitHub and want reuse +# the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code -# fragments. Normal C and C++ comments will always remain visible. +# fragments. Normal C, C++ and Fortran comments will always remain visible. -STRIP_CODE_COMMENTS = YES +STRIP_CODE_COMMENTS = NO # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = NO #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 3 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = @US_DOXYGEN_HTML_OUTPUT@ # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = @US_DOXYGEN_HEADER@ # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = @US_DOXYGEN_FOOTER@ # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If the tag is left blank doxygen -# will generate a default style sheet. Note that doxygen will try to copy -# the style sheet file to the HTML output directory, so don't put your own -# style sheet in the HTML output directory as well, or it will be erased! +# fine-tune the look of the HTML output. If left blank doxygen will +# generate a default style sheet. Note that it is recommended to use +# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this +# tag will in the future become obsolete. + +HTML_STYLESHEET = -HTML_STYLESHEET = @US_DOXYGEN_CSS@ +# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional +# user-defined cascading style sheet that is included after the standard +# style sheets created by doxygen. Using this option one can overrule +# certain style aspects. This is preferred over using HTML_STYLESHEET +# since it does not replace the standard style sheet and is therefor more +# robust against future updates. Doxygen will copy the style sheet file to +# the output directory. + +HTML_EXTRA_STYLESHEET = @US_DOXYGEN_EXTRA_CSS@ # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of # entries shown in the various tree structured indices initially; the user # can expand and collapse entries dynamically later on. Doxygen will expand # the tree to such a level that at most the specified number of entries are # visible (unless a fully collapsed tree already exceeds this amount). # So setting the number of entries 1 will produce a full collapsed tree by # default. 0 is a special value representing an infinite number of entries # and will result in a full expanded tree by default. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project -# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. +# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely +# identify the documentation publisher. This should be a reverse domain-name +# style string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = NO # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 300 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO +# When MathJax is enabled you can set the default output format to be used for +# thA MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and +# SVG. The default value is HTML-CSS, which is slower, but has the best +# compatibility. + +MATHJAX_FORMAT = HTML-CSS + # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to # the MathJax Content Delivery Network so you can quickly see the result without # installing MathJax. # However, it is strongly recommended to install a local # copy of MathJax from http://www.mathjax.org before deployment. MATHJAX_RELPATH = http://www.mathjax.org/mathjax # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be -# implemented using a PHP enabled web server instead of at the web client -# using Javascript. Doxygen will generate the search PHP script and index -# file to put on the web server. The advantage of the server -# based approach is that it scales better to large projects and allows -# full text search. The disadvantages are that it is more difficult to setup -# and does not have live searching capabilities. +# implemented using a web server instead of a web client using Javascript. +# There are two flavours of web server based search depending on the +# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for +# searching and an index file used by the script. When EXTERNAL_SEARCH is +# enabled the indexing and searching needs to be provided by external tools. +# See the manual for details. SERVER_BASED_SEARCH = NO +# When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP +# script for searching. Instead the search results are written to an XML file +# which needs to be processed by an external indexer. Doxygen will invoke an +# external search engine pointed to by the SEARCHENGINE_URL option to obtain +# the search results. Doxygen ships with an example indexer (doxyindexer) and +# search engine (doxysearch.cgi) which are based on the open source search engine +# library Xapian. See the manual for configuration details. + +EXTERNAL_SEARCH = NO + +# The SEARCHENGINE_URL should point to a search engine hosted by a web server +# which will returned the search results when EXTERNAL_SEARCH is enabled. +# Doxygen ships with an example search engine (doxysearch) which is based on +# the open source search engine library Xapian. See the manual for configuration +# details. + +SEARCHENGINE_URL = + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed +# search data is written to a file for indexing by an external tool. With the +# SEARCHDATA_FILE tag the name of this file can be specified. + +SEARCHDATA_FILE = searchdata.xml + +# When SERVER_BASED_SEARCH AND EXTERNAL_SEARCH are both enabled the +# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is +# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple +# projects and redirect the results back to the right project. + +EXTERNAL_SEARCH_ID = + +# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen +# projects other than the one defined by this configuration file, but that are +# all added to the same external search index. Each project needs to have a +# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id +# of to a relative location where the documentation can be found. +# The format is: EXTRA_SEARCH_MAPPINGS = id1=loc1 id2=loc2 ... + +EXTRA_SEARCH_MAPPINGS = + #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = amssymb # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = YES # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = @PROJECT_BINARY_DIR@/include/ # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = *.h # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = US_PREPEND_NAMESPACE(x)=x \ US_BEGIN_NAMESPACE= \ US_END_NAMESPACE= \ - "US_BASECLASS_NAME=@US_BASECLASS_NAME@" \ US_EXPORT= \ US_ABI_LOCAL= \ US_MSVC_POP_WARNING= # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. For each # tag file the location of the external documentation should be added. The # format of a tag file without this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths # or URLs. Note that each tag file must have a unique name (where the name does # NOT include the path). If a tag file is not located in the directory in which # doxygen is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = NO # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = @US_HAVE_DOT@ # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = @US_DOXYGEN_DOT_NUM_THREADS@ # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = FreeSans.ttf # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If the UML_LOOK tag is enabled, the fields and methods are shown inside # the class node. If there are many fields or methods and many nodes the # graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS # threshold limits the number of items for each type to make the size more # managable. Set this to 0 for no limit. Note that the threshold may be # exceeded by 50% before the limit is enforced. UML_LIMIT_NUM_FIELDS = 10 # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = NO # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = NO # If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = NO # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = NO # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = @US_DOXYGEN_DOT_PATH@ # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES diff --git a/Core/CppMicroServices/documentation/doxygen/MicroServices.dox b/Core/CppMicroServices/documentation/doxygen/MicroServices.dox new file mode 100644 index 0000000000..86032cd9d6 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices.dox @@ -0,0 +1,126 @@ + +/** + +\defgroup MicroServices Micro Services Classes + +\brief This category includes classes related to the C++ Micro Services component. + +The C++ Micro Services component provides a dynamic service registry based on the service layer +as specified in the OSGi R4.2 specifications. + +*/ + +/** + +\defgroup MicroServicesUtils Utility Classes + +\brief This category includes utility classes which can be used by others. + +*/ + +/** + +\defgroup MicroServicesCMake CMake Functions + +\brief This category includes CMake utility functions for external projects. + +External projects can include the CMake scripts provided by the CppMicroServices +library to automatically generate module initialization code and to embed external resources +into a modules shared library. + +*/ + +/** + +\page MicroServices_Tutorials Tutorial + +This tutorial creates successively more complex modules to illustrate +most of the features and functionality offered by the C++ Micro Services library. +It is heavily base on the Apache Felix OSGi Tutorial. + +- \subpage MicroServices_Example1 +- \subpage MicroServices_Example2 +- \subpage MicroServices_Example2b +- \subpage MicroServices_Example3 +- \subpage MicroServices_Example4 +- \subpage MicroServices_Example5 +- \subpage MicroServices_Example6 +- \subpage MicroServices_Example7 + +*/ + +/** + +\page MicroServices_UserDocs User Documentation + +This is a list of available documentation for different aspects of the C++ +Micro Services library: + +\if us_standalone +- \subpage BuildInstructions +- \subpage MicroServices_GettingStarted +\endif +- \subpage MicroServices_TheModuleContext +- \subpage MicroServices_Resources +- \subpage MicroServices_ModuleProperties +- \subpage MicroServices_AutoLoading +- \subpage MicroServices_StaticModules +- \subpage MicroServices_EmulateSingleton + +*/ + +/** + +\embmainpage{MicroServices_Overview} The C++ Micro Services + +The C++ Micro Services library provides a dynamic service registry based on the service layer +as specified in the OSGi R4.2 specifications. It enables users to realize a service oriented +approach within their software stack. The advantages include higher reuse of components, looser +coupling, better organization of responsibilities, cleaner API contracts, etc. + +\if us_standalone +\section MicroServices_Overview_BI Build Instructions + +How to build the C++ Micro Services library is explained in detail on the \ref BuildInstructions page. +\endif + +

Tutorial

+ +\if us_standalone +Here is a list of \ref MicroServices_Tutorials "tutorial examples" +\else +Here is a list of \subpage MicroServices_Tutorials "tutorial examples" +\endif +which create successively more complex modules to illustrate most of the features and +functionality offered by the C++ Micro Services library: + +- \ref MicroServices_Example1 +- \ref MicroServices_Example2 +- \ref MicroServices_Example2b +- \ref MicroServices_Example3 +- \ref MicroServices_Example4 +- \ref MicroServices_Example5 +- \ref MicroServices_Example6 +- \ref MicroServices_Example7 + +

User Documentation

+ +The links in the following list point to important +\if us_standalone +\ref MicroServices_UserDocs "user documentation": +\else +\subpage MicroServices_UserDocs "user documentation": +\endif + +\if us_standalone +- \ref BuildInstructions +- \ref MicroServices_GettingStarted +\endif +- \ref MicroServices_TheModuleContext +- \ref MicroServices_Resources +- \ref MicroServices_ModuleProperties +- \ref MicroServices_AutoLoading +- \ref MicroServices_StaticModules +- \ref MicroServices_EmulateSingleton + +*/ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md similarity index 74% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md index 7e2ca58433..66a39cbb95 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md @@ -1,78 +1,86 @@ Auto Loading Modules {#MicroServices_AutoLoading} ==================== Auto-loading of modules is a feature of the CppMicroServices library to manage the loading of modules which would normally not be loaded at runtime because of missing link-time dependencies. The Problem ----------- Imagine that you have a module *A* which provides an interface for loading files and another module *B* which registers a service implementing that interface for files of type *png*. Your executable *E* uses the interface from *A* to query the service registry for available services. Due to the link-time dependencies, this results in the following dependency graph: \dot digraph linker_deps { node [shape=record, fontname=Helvetica, fontsize=10]; a [ label="Module A\n(Interfaces)" ]; b [ label="Module B\n(service provider)" ]; e [ label="Executable E\n(service consumer)" ]; a -> e; a -> b; } \enddot When the executable *E* is launched, the dynamic linker of your operating system loads module *A* to satisfy the dependencies of *E*, but module *B* will not be loaded. Therefore, the executable will not be able to consume any services from module *B*. The Solution ------------ The problem above is solved in the CppMicroServices library by automatically loading modules from a list of configurable file-system locations. For each module being loaded, the following steps are taken: - If the module provides an activator, it's ModuleActivator::Load() method is called. - If auto-loading is enabled, and the module declared a non-empty auto-load directory, the auto-load paths returned from ModuleSettings::GetAutoLoadPaths() are processed. - For each auto-load path, all modules in that path with the currently loaded module's auto-load directory appended are explicitly loaded. -See the ModuleSettings class for details about auto-load paths and the #US_INITIALIZE_MODULE -macro for details about a module's auto-load directory. +See the ModuleSettings class for details about auto-load paths. The auto-load directory of +a module defaults to the module's library name, but can be customized using a `manifest.json` +file (see \ref MicroServices_ModuleProperties). For executables, the auto-load directory +defaults to the special value `main`. This allows third-party modules to be auto-loaded +during application start-up, without having to reference a special auto-load directory. If module *A* in the example above contains initialization code like \code -US_INITIALIZE_MODULE("Module A", "A", "", "1.0.0") +US_INITIALIZE_MODULE("Module A", "A") \endcode and the module's library is located at /myproject/libA.so all libraries located at /myproject/A/ will be automatically loaded (unless the auto-load paths have been modified). By ensuring that module *B* from the example above is located at /myproject/A/libB.so it will be loaded when the executable *E* is started and is then able to register its services before the executable queries the service registry. +\note If you need to add additional auto-load search paths during application start-up, provide +a ModuleActivator instance in your executable and call ModuleSettings::AddAutoLoadPath() in +your executable's ModuleActivator::Load() method. If there are modules inside a `main` sub-directory +of any of the provided auto-load search paths, these modules will then be auto-loaded before +your executable's main() function is executed. + Environment Variables --------------------- The following environment variables influence the runtime behavior of the CppMicroServices library: - + - *US_DISABLE_AUTOLOADING* If set, auto-loading of modules is disabled. - *US_AUTOLOAD_PATHS* A `:` (Unix) or `;` (Windows) separated list of paths from which modules should be auto-loaded. - diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox b/Core/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox similarity index 100% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox rename to Core/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox b/Core/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox similarity index 95% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox rename to Core/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox index 0b3094f105..55e51753e9 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox @@ -1,91 +1,89 @@ /** \page MicroServices_EmulateSingleton Emulating singletons with micro services \section MicroServices_EmulateSingleton_1 Meyers Singleton Singletons are a well known pattern to ensure that only one instance of a class exists during the whole life-time of the application. A self-deleting variant is the "Meyers Singleton": \snippet uServices-singleton/SingletonOne.h s1 where the GetInstance() method is implemented as \snippet uServices-singleton/SingletonOne.cpp s1 If such a singleton is accessed during static deinitialization (which happens during unloading of shared libraries or application termination), your program might crash or even worse, exhibit undefined behavior, depending on your compiler and/or weekday. Such an access might happen in destructors of other objects with static life-time. For example, suppose that SingletonOne needs to call a second Meyers singleton during destruction: \snippet uServices-singleton/SingletonOne.cpp s1d If SingletonTwo was destroyed before SingletonOne, this leads to the mentioned problems. Note that this problem only occurs for static objects defined in the same shared library. Since you cannot reliably control the destruction order of global static objects, you must not introduce dependencies between them during static deinitialization. This is one reason why one should consider an alternative approach to singletons (unless you can absolutely make sure that nothing in your shared library will introduce such dependencies. Never.) Of course you could use something like a "Phoenix singleton" but that will have other drawbacks in certain scenarios. Returning pointers instead of references in GetInstance() would open up the possibility to return NULL, but than again this would not help if you require a non-NULL instance in your destructor. Another reason for an alternative approach is that singletons are usually not meant to be singletons for eternity. If your design evolves, you might hit a point where you suddenly need multiple instances of your singleton. \section MicroServices_EmulateSingleton_2 Singletons as a service The C++ Micro Services can be used to emulate the singleton pattern using a non-singleton class. This leaves room for future extensions without the need for heavy refactoring. Additionally, it gives you full control about the construction and destruction order of your "singletons" inside your shared library or executable, making it possible to have dependencies between them during destruction. \subsection MicroServices_EmulateSingleton_2_1 Converting a classic singleton We modify the previous SingletonOne class such that it internally uses the micro services API. The changes are discussed in detail below. \snippet uServices-singleton/SingletonOne.h ss1 - - Inherit us::Base: All service implementations (not their interfaces) must inherit from us::Base or from the base - class as specified in the CMake configuration. - In the implementation above, the class SingletonOneService provides the implementation as well as the interface. + - In the implementation above, the class SingletonOneService provides the implementation as well as the interface. - Friend activator: We move the responsibility of constructing instances of SingletonOneService from the GetInstance() method to the module activator. - Service interface declaration: Because the SingletonOneService class introduces a new service interface, it must be registered under a unique name using the helper macro US_DECLARE_SERVICE_INTERFACE. - + Let's have a look at the modified GetInstance() and ~SingletonOneService() methods. \snippet uServices-singleton/SingletonOne.cpp ss1gi The inline comments should explain the details. Note that we now had to change the return type to a pointer, instead of a reference as in the classic singleton. This is necessary since we can no longer guarantee that an instance always exists. Clients of the GetInstance() method must check for null pointers and react appropriately. \warning Newly created "singletons" should not expose a GetInstance() method. They should be handled as proper services and hence should be retrieved by clients using the ModuleContext or ServiceTracker API. The GetInstance() method is for migration purposes only. \snippet uServices-singleton/SingletonOne.cpp ss1d The SingletonTwoService::GetInstance() method is implemented exactly as in SingletonOneService. Because we know that the module activator guarantees that a SingletonTwoService instance will always be available during the life-time of a SingletonOneService instance (see below), we can assert a non-null pointer. Otherwise, we would have to handle the null-pointer case. The order of construction/registration and destruction/unregistration of our singletons (or any other services) is defined in the Load() and Unload() methods of the module activator. \snippet uServices-singleton/main.cpp 0 The Unload() method is defined as: \snippet uServices-singleton/main.cpp 1 */ diff --git a/Core/CppMicroServices/documentation/doxygen/MicroServices_ModuleProperties.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_ModuleProperties.md new file mode 100644 index 0000000000..29464ae39b --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_ModuleProperties.md @@ -0,0 +1,51 @@ +Module Properties {#MicroServices_ModuleProperties} +================= + +A C++ Micro Services Module provides meta-data in the form of so-called *properties* about itself. +Properties are key - value pairs where the key is of type `std::string` and the value of type `Any`. +The following properties are always set by the C++ Micro Services library and cannot be altered by +the module author: + + * `module.id` - The unique id of the module (type `long`) + * `module.name` - The human readable name of the module (type `std::string`) + * `module.location` - The full path to the module's shared library on the file system (type `std::string`) + +Module authors can add custom properties by providing a `manifest.json` file, embedded as a top-level +resource into the module (see \ref MicroServices_Resources). The root value of the Json file must be +a Json object. An example `manifest.json` file would be: + +~~~{.json} +{ + "module.version" : "1.0.2", + "module.description" : "This module provides an awesome service", + "authors" : [ "John Doe", "Douglas Reynolds", "Daniel Cannady" ], + "rating" : 5 +} +~~~ + +All Json member names of the root object will be available as property keys in the module containing +the `manifest.json` file. The C++ Micro Services library specifies the following standard keys for +re-use in `manifest.json` files: + + * `module.version` - The version of the module (type `std::string`). The version string must be a + valid version identifier, as specified in the ModuleVersion class. + * `module.vendor` - The vendor name of the module (type `std::string`) + * `module.description` - A description for the module (type `std::string`) + * `module.autoload_dir` - A custom auto-load directory for the module (type `std::string`). If not + set, this property defaults to the module's library name. + +\note Some of the properties mentioned above may also be accessed via dedicated methods in the Module class, +e.g. Module::GetName() or Module::GetVersion(). + +When parsing the `manifest.json` file, the Json types are mapped to C++ types and stored in instances of +the Any class. The mapping is as follows: + +| Json | C++ (%Any) | +|-------|-----------| +|object | std::map | +|array | std::vector | +|string | std::string | +|number | int or double | +|true | bool | +|false | bool | +|null | %Any() | diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_Resources.md similarity index 94% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_Resources.md index da80b20349..101044d143 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_Resources.md @@ -1,56 +1,56 @@ The Resources System {#MicroServices_Resources} ==================== The C++ Micro Services library provides a generic resources system to embed arbitrary files into a module's shared library (the current size limitation is based on the largest source code file size your compiler can handle). The following features are supported: * Embed arbitrary data into shared or static modules or executables. * Data is embedded in a compressed format if the size reduction exceeds a configurable threshold. * Resources are accessed via a Module instance, providing individual resource lookup and access for each module. * Resources are managed in a tree hierarchy, modeling the original child - parent relationship on the file-system. * The ModuleResource class provides a high-level API for accessing resource information and traversing the resource tree. * The ModuleResourceStream class provides an STL input stream derived class for the seamless usage of embedded resource data in third-party libraries. Embedding Resources in a %Module -------------------------------- +-------------------------------- Resources are embedded by compiling a source file generated by the `usResourceCompiler` executable into a module's shared or static library (or into an executable). -If you are using CMake, consider using the provided `usFunctionEmbedResources` CMake macro which +If you are using CMake, consider using the provided `#usFunctionEmbedResources` CMake macro which handles the invocation of the `usResourceCompiler` executable and sets up the correct file dependencies. Accessing Resources at Runtime ------------------------------ Each module provides access to its embedded resources via the Module class which provides methods returning ModuleResource objects. The ModuleResourceStream class provides a std::istream compatible object to access the resource contents. The following example shows how to retrieve a resource from each currently loaded module whose path is specified by a module property: \snippet uServices-resources/main.cpp 2 This example could be enhanced to dynamically react to modules being loaded and unloaded, making use of the popular "extender pattern" from OSGi. Limitations ----------- Currently, the system has the following limitations: * At most one file generated by the `usResourceCompiler` executable can be compiled into a module's shared library (you can work around this limitation by creating static modules and importing them). * The size of embedded resources is limited by the file size your compiler can handle. However, the file size is the sum of the size of all resources embedded into a module plus a small overhead. diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md similarity index 84% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md index a62d196755..344cfb5146 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md @@ -1,92 +1,90 @@ Static Modules {#MicroServices_StaticModules} ============== The normal and most flexible way to include a CppMicroServices module in an application is to compile it into a shared library that is either linked by another library (or executable) or \ref MicroServices_AutoLoading "auto-loaded" during runtime. However, modules can be linked statically to your application or shared library. This makes the deployment of your application less error-prone and in the case of a complete static build also minimizes its binary size and start-up time. The disadvantage is that no functionality can be added without a rebuild and redistribution of the application. -## Creating Static Modules +# Creating Static Modules Static modules are written just like shared modules - there are no differences in the usage of the CppMicroServices API or the provided preprocessor macros. The only thing you need to make sure is that the `US_STATIC_MODULE` preprocessor macro is defined when building a module statically. -## Using Static Modules +# Using Static Modules Static modules can be used (imported) in shared or other static libraries or in the executable itself. Assuming that a static module makes use of the CppMicroServices API (e.g. by registering some services -using a ModuleContext), the importing library or executable needs to put a call to the `#US_INITIALIZE_MODULE` macro -somewhere in its source code. This ensures the availability of a module context which is shared with all -imported static libraries (see also \ref MicroServices_StaticModules_Context). +using a ModuleContext), the importing library or executable needs to put a call to the `#US_INITIALIZE_MODULE` +or the `#US_INITIALIZE_EXECUTABLE` macro somewhere in its source code. This ensures the availability of +a module context which is shared with all imported static libraries (see also \ref MicroServices_StaticModules_Context). \note Note that if your static module does not export a module activator by using the macro `#US_EXPORT_MODULE_ACTIVATOR` or does not contain embedded resources (see \ref MicroServices_Resources) you do not need to put the special import macros explained below into your code. You can use and link the static module just like any other static library. For every static module you would like to import, you need to put a call to `#US_IMPORT_MODULE` into the source code of the importing library. To make the static module's resources available to the importing module, you must also call `#US_IMPORT_MODULE_RESOURCES`. Addidtionally, you need a call to `#US_LOAD_IMPORTED_MODULES` which contains a space-deliminated list of module names in the importing libaries source code. This ensures that the module activators of the imported static modules (if they exist) are called appropriately and that the embedded resources are registered with the importing module. \note When importing a static module into another static module, the call to `#US_LOAD_IMPORTED_MODULES` in the importing static module will have no effect. This macro can only be used in shared modules or executables. There are two main usage scenarios which are explained below together with some example code. -### Using a Shared CppMicroServices Library +## Using a Shared CppMicroServices Library Building the CppMicroServices library as a shared library allows you to import static modules into other shared or static modules or into the executable. As noted above, the importing shared module or executable -needs to provide a module context by calling the `#US_INITIALIZE_MODULE` macro. Additionally, you must ensure -to use the `#US_LOAD_IMPORTED_MODULES_INTO_MAIN` macro instead of `#US_LOAD_IMPORTED_MODULES` when importing -static modules into an executable. +needs to provide a module context by calling the `#US_INITIALIZE_MODULE` or `#US_INITIALIZE_EXECUTABLE` macro. +Additionally, you must ensure to use the `#US_LOAD_IMPORTED_MODULES_INTO_MAIN` macro instead of +`#US_LOAD_IMPORTED_MODULES` when importing static modules into an executable. Example code for importing the two static modules `MyStaticModule1` and `MyStaticModule2` into an executable: \snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoMain Importing the static module `MyStaticModule` into a shared or static module looks like this: \snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoLib Having a shared CppMicroServices library, the executable also needs some initialization code: \snippet uServices-staticmodules/main.cpp InitializeExecutable -Note that shared (but not static) modules also need the `#US_INITIALIZE_MODULE` call when importing static modules, -but can omit the US_BUILD_SHARED_LIBS guard. +Note that shared (but not static) modules also need the `#US_INITIALIZE_MODULE` call when importing static modules. -### Using a Static CppMicroServices Library +## Using a Static CppMicroServices Library The CppMicroServices library can be build as a static library. In that case, creating shared modules is not supported. If you create shared modules which link a static version of the CppMicroServices library, the runtime behavior is undefined. In this usage scenario, every module will be statically build and linked to an executable. The executable needs to import all the static modules, just like above: \snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoMain However, it can omit the `#US_INITIALIZE_MODULE` macro call (the module context from the CppMicroServices library will be shared across all modules and the executable). -## A Note About The Module Context {#MicroServices_StaticModules_Context} +# A Note About The Module Context {#MicroServices_StaticModules_Context} Modules using the CppMicroServices API frequently need a `ModuleContext` object to query, retrieve, and register services. Static modules will never get their own module context but will share the context with their importing module or executable. Therefore, the importing module or executable needs to ensure the availability of such a context (by using -the `#US_INITIALIZE_MODULE` macro). +the `#US_INITIALIZE_MODULE` or `#US_INITIALIZE_EXECUTABLE` macro). \note The CppMicroServices library will *always* provide a module context, independent of its library build mode. So in a completely statically build application, the CppMicroServices library provides a global module context for all imported modules and the executable. - diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md b/Core/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md similarity index 75% rename from Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md rename to Core/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md index dc7b9cda42..f35054b556 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md +++ b/Core/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md @@ -1,36 +1,37 @@ The Module Context {#MicroServices_TheModuleContext} =================== In the context of the C++ Micro Services library, we will call all supported "shared library" types (DLL, DSO, DyLib, etc.) uniformly a *module*. A module accesses the C++ Micro Services API via a ModuleContext object. While multiple modules could use the same ModuleContext, it is highly recommended that each module gets its own (this will enable module specific service usage tracking and also allows the C++ Micro Services framework to properly cleanup resources after a module has been unloaded). ### Creating a ModuleContext To create a ModuleContext object for a specific library, you have two options. If your project uses -CMake as the build system, use the supplied `usFunctionGenerateModuleInit` CMake function to automatically +CMake as the build system, use the supplied `#usFunctionGenerateModuleInit` CMake function to automatically create a source file and add it to your module's sources: - set(module_srcs ) - usFunctionGenerateModuleInit(module_srcs - NAME "My Module" - LIBRARY_NAME "mylibname" - VERSION "1.0.0" - ) - add_library(mylib ${module_srcs}) - +~~~{.cpp} +set(module_srcs ) +usFunctionGenerateModuleInit(module_srcs + NAME "My Module" + LIBRARY_NAME "mylibname" + ) +add_library(mylib ${module_srcs}) +~~~ + If you do not use CMake, you have to add a call to the macro `#US_INITIALIZE_MODULE` in one of the source files of your module: \snippet uServices-modulecontext/main.cpp InitializeModule ### Getting a ModuleContext To retrieve the module specific ModuleContext object from anywhere in your module, use the `#GetModuleContext` function: \snippet uServices-modulecontext/main.cpp GetModuleContext Please note that the call to `#GetModuleContext` will fail if you did not create a module specific context. diff --git a/Core/CppMicroServices/documentation/doxygen/doxygen_extra.css b/Core/CppMicroServices/documentation/doxygen/doxygen_extra.css new file mode 100644 index 0000000000..4328573360 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/doxygen_extra.css @@ -0,0 +1,283 @@ + +#MSearchField { + height: 14px; +} + +#MSearchClose { + top: 1px; +} + +#MSearchResultsWindow { + z-index: 200; +} + +body { + background-color: inherit; +} + +body, table, div, p, dl { + font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; + font-size: 13px; + line-height: 18px; + color: #333333; +} + +h1 { + font-size: 150%; +} + +h2 { + font-size: 120%; +} + +h3 { + font-size: 100%; +} + +a { + color: #0088CC; +} + +div#top { + background-color: #F5F5F5; + margin: -20px -20px 20px; +} + +.tabs, .tabs2, .tabs3 { + font-size: 16px; + position: relative; + background-image: none; +} + +.tabs2 { + font-size: 14px; +} +.tabs3 { + font-size: 12px; +} + +.tablist li { + background-image: none; + line-height: inherit; +} + +.tablist a { + background-image: none; + padding: 10px 20px; + color: #999999; +} + +.tablist a:hover { + text-decoration: underline; + background-image: none; + text-shadow: none; + color: #999999; +} + +.tablist li.current a { + background-image: none; + background-color: #BBBBBB; + text-shadow: none; +} + +div.qindex, div.navtab { + background-color: inherit; + border: 1px solid #e6e6e6; +} + +h2.groupheader { + border: none; + font-size: 120%; + font-weight: bold; + color: #333333; +} + +pre.fragment { + border: none; + border-top-style: solid; + border-bottom-style: solid; + border-width: 1px 0 1px 0; + border-color: #e6e6e6; + border-radius: 0; +} + +div.fragment { + padding: 4px 6px; + margin: 4px 8px 4px 2px; + border: none; + border-top-style: solid; + border-bottom-style: solid; + border-width: 1px 0 1px 0; + border-color: #e6e6e6; + background-color: #F5F5F5; +} + +div.line { + -webkit-transition-property: none; + -moz-transition-property: none; + -ms-transition-property: none; + -o-transition-property: none; + transition-property: none; +} + +div.ah { + background-color: #f6f6f6; + border: solid thin #e6e6e6; + box-shadow: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + background-image: none; + color: #333333; +} + +td.indexkey, td.indexvalue { + background-color: inherit; + border: none; +} + +tr.separator\3A, td.memSeparator { + display: none; +} + +hr { + border-top: 1px solid #e6e6e6; +} + +.mdescLeft, .mdescRight, +.memItemLeft, .memItemRight, +.memTemplItemLeft, .memTemplItemRight, .memTemplParams { + background-color: inherit; +} + +.memItemLeft, .memItemRight, .memTemplParams { + border: none; +} + +.memproto, dl.reflist dt { + border-top: 1px solid #e6e6e6; + border-left: 1px solid #e6e6e6; + border-right: 1px solid #e6e6e6; + text-shadow: none; + background-image: none; + background-color: #f6f6f6; + /* opera specific markup */ + box-shadow: none; + border-top-right-radius: 8px; + border-top-left-radius: 8px; + /* firefox specific markup */ + -moz-box-shadow: none; + -moz-border-radius-topright: 8px; + -moz-border-radius-topleft: 8px; + /* webkit specific markup */ + -webkit-box-shadow: none; + -webkit-border-top-right-radius: 8px; + -webkit-border-top-left-radius: 8px; +} + +.memdoc, dl.reflist dd { + border-bottom: 1px solid #e6e6e6; + border-left: 1px solid #e6e6e6; + border-right: 1px solid #e6e6e6; + padding: 2px 5px; + background-color: inherit; + background-image: none; + border-top-width: 0; + /* opera specific markup */ + border-bottom-left-radius: 8px; + border-bottom-right-radius: 8px; + box-shadow:none; + /* firefox specific markup */ + -moz-border-radius-bottomleft: 8px; + -moz-border-radius-bottomright: 8px; + -moz-box-shadow: none; + /* webkit specific markup */ + -webkit-border-bottom-left-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + -webkit-box-shadow: none; +} + +.paramname code { + line-height: inherit; +} + +.params .paramname, .tparams .paramname, .retval .paramname { + padding-right: 10px; +} + +span.mlabel { + border-top:1px solid #405C93; + border-left:1px solid #405C93; +} + +div.directory { + border: none; +} + +.directory td { + vertical-align: baseline; +} + +.directory tr.even { + background-color: inherit; +} + +address { + color: inherit; + margin: 0; +} + +.navpath ul +{ + background-image: none; + height: auto; + line-height: inherit; + color: inherit; + border: none; +} + +.navpath li +{ + background-image: none; + color: inherit; +} + +.navpath li.navelem a +{ + height:22px; + color: #999; +} + +.navpath li.navelem a:hover +{ + text-decoration: underline; +} + +div.ingroups +{ + margin-left: 5px; + padding-left: 5px; +} + +div.header +{ + background-image: none; + background-color: inherit; + border-bottom: 1px solid #333333; +} + +div.headertitle +{ + padding: 0px 5px 0px 7px; +} + +dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug +{ + margin-left: 12px; +} + +code { + background-color: none; + border: none; + color: #333333; + padding: 1; +} diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example1.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example1.md new file mode 100644 index 0000000000..e5c92e2981 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example1.md @@ -0,0 +1,97 @@ +Example 1 - Service Event Listener {#MicroServices_Example1} +================================== + +This example creates a simple module that listens for service events. +This example does not do much at first, because it only prints out the details +of registering and unregistering services. In the next example we will create +a module that implements a service, which will cause this module to actually +do something. For now, we will just use this example to help us understand the +basics of creating a module and its activator. + +A module gains access to the C++ Micro Services API using a unique instance +of ModuleContext. This unique module context can be used during static +initialization of the module or at any later point during the life-time of the +module. To execute code during static initialization (and de-initialization) +time, the module must provide an implementation of the ModuleActivator interface; +this interface has two methods, Load() and Unload(), that both receive the +module's context and are called when the module is loaded (statically initialized) +and unloaded, respectively. + +\note You do not need to remember the ModuleContext instance within the +ModuleActivator::Load() method and provide custom access methods for later +retrieval. Use the GetModuleContext() function to easily retrieve the current +module's context. + +In the following source code, our module implements +the ModuleActivator interface and uses the context to add itself as a listener +for service events (in the `eventlistener/Activator.cpp` file): + +\snippet eventlistener/Activator.cpp Activator + +After implementing the C++ source code for the module activator, we must *export* +the activator such that the C++ Micro Services library can create an instance +of it and call the `Load()` and `Unload()` methods: + +\dontinclude eventlistener/Activator.cpp +\skipline US_EXPORT + +Now we need to compile the source code. This example uses CMake as the build +system and the top-level CMakeLists.txt file could look like this: + +\dontinclude examples/CMakeLists.txt +\skip project +\until eventlistener + +and the CMakeLists.txt file in the eventlistener subdirectory is: + +\include eventlistener/CMakeLists.txt + +The call to `#usFunctionGenerateModuleInit` is necessary to integrate the shared +library as a module within the C++ Micro Service library. If you are not using +CMake, you have to place a macro call to `#US_INITIALIZE_MODULE` yourself into the +module's source code, e.g. in `Activator.cpp`. Have a look at the +\ref MicroServices_GettingStarted documentation for more details about using CMake +or other build systems (e.g. Makefiles) when writing modules. + +To run the examples contained in the C++ Micro Services library, we use a small +driver program called `CppMicroServicesExampleDriver`: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> h +h This help text +l Load the module with id or name +u Unload the module with id +s Print status information +q Quit +> +\endverbatim + +Typing `s` at the command prompt lists the available, loaded, and unloaded modules. +To load the eventlistener module, type `l eventlistener` at the command prompt: + +\verbatim +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | dictionaryservice | - + - | eventlistener | - + - | frenchdictionary | - + - | spellcheckclient | - + - | spellcheckservice | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> +\endverbatim + +The above command loaded the eventlistener module (by loading its shared library). +Keep in mind, that this module will not do much at this point since it only +listens for service events and we are not registering any services. In the next +example we will register a service that will generate an event for this module to +receive. To exit the `CppMicroServicesExampleDriver`, use the `q` command. + +Next: \ref MicroServices_Example2 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2.md new file mode 100644 index 0000000000..b7fe0bbca3 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2.md @@ -0,0 +1,87 @@ +Example 2 - Dictionary Service Module {#MicroServices_Example2} +===================================== + +This example creates a module that implements a service. Implementing a +service is a two-step process, first we must define the interface of the service +and then we must define an implementation of the service interface. In this +particular example, we will create a dictionary service that we can use to check +if a word exists, which indicates if the word is spelled correctly or not. First, +we will start by defining a simple dictionary service interface in a file called +`dictionaryservice/IDictionaryService.h`: + +\snippet dictionaryservice/IDictionaryService.h service + +The service interface is quite simple, with only one method that needs to be +implemented. Because we provide an empty out-of-line destructor (defined in the +file `IDictionaryService.cpp`) we must export the service interface by using the +module specific `DICTIONARYSERVICE_EXPORT` macro. + +In the following source code, the module uses its module context +to register the dictionary service. We implement the dictionary service as an +inner class of the module activator class, but we could have also put it in a +separate file. The source code for our module is as follows in a file called +`dictionaryservice/Activator.cpp`: + +\snippet dictionaryservice/Activator.cpp Activator + +Note that we do not need to unregister the service in the Unload() method, +because the C++ Micro Services library will automatically do so for us. The +dictionary service that we have implemented is very simple; its dictionary +is a set of only five words, so this solution is not optimal and is only +intended for educational purposes. + +\note In this example, the service interface and implementation are both +contained in one module which exports the interface class. However, service +implementations almost never need to be exported and in many use cases +it is beneficial to provide the service interface and its implementation(s) +in separate modules. In such a scenario, clients of a service will only +have a link-time dependency on the shared library providing the service interface +(because of the out-of-line destructor) but not on any modules containing +service implementations. This often leads to modules which do not export +any symbols at all and hence need to be loaded into the running process +manually or by using the \ref MicroServices_AutoLoading "auto-loading mechanism". + +For an introduction how to compile our source code, see \ref MicroServices_Example1. + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load our dictionary service module by typing +the `l dictionaryservice` command: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> s +Id | Name | Status +----------------------------------- + - | dictionaryservice | - + - | eventlistener | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> l dictionaryservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED +> +\endverbatim + +To unload the module, use the `u ` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its dictionary service. Using the `CppMicroServicesExampleDriver` +commands `u` and `l` we can unload and load it at will, respectively. Each +time we load and unload our dictionary service module, we should see the details +of the associated service event printed from the module from Example 1. In +\ref MicroServices_Example3 "Example 3", we will create a client for our +dictionary service. To exit `CppMicroServicesExampleDriver`, we use the `q` command. + +Next: \ref MicroServices_Example2b + +Previous: \ref MicroServices_Example1 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2b.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2b.md new file mode 100644 index 0000000000..4045a8e483 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example2b.md @@ -0,0 +1,76 @@ +Example 2b - Alternative Dictionary Service Module {#MicroServices_Example2b} +================================================== + +This example creates an alternative implementation of the dictionary service +defined in \ref MicroServices_Example2 "Example 2". The source code for the +module is identical except that instead of using English words, French words +are used. The only other difference is that in this module we do not need to +define the dictionary service interface again, since we can just link the +definition from the module in Example 2. The main point of this example is +to illustrate that multiple implementations of the same service may exist; +this example will also be of use to us in \ref MicroServices_Example5 "Example 5". + +In the following source code, the module uses its module context +to register the dictionary service. We implement the dictionary service as an +inner class of the module activator class, but we could have also put it in a +separate file. The source code for our module is as follows in a file called +`dictionaryclient/Activator.cpp`: + +\snippet frenchdictionary/Activator.cpp Activator + +For an introduction how to compile our source code, see \ref MicroServices_Example1. +Because we use the `IDictionaryService` definition from Example 2, we also +need to make sure that the proper include paths and linker dependencies are set: + +\include frenchdictionary/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load our dictionary service module by typing +the `l frenchdictionary` command: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> s +Id | Name | Status +----------------------------------- + - | dictionaryservice | - + - | eventlistener | - + - | frenchdictionary | - + 1 | CppMicroServices | LOADED +> l eventlistener +Starting to listen for service events. +> l frenchdictionary +Ex1: Service of type IDictionaryService/1.0 registered. +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | French Dictionary | LOADED +> +\endverbatim + +To unload the module, use the `u ` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its dictionary service. Using the `CppMicroServicesExampleDriver` +commands `u` and `l` we can unload and load it at will, respectively. Each +time we load and unload our dictionary service module, we should see the details +of the associated service event printed from the module from Example 1. In +\ref MicroServices_Example3 "Example 3", we will create a client for our +dictionary service. To exit `CppMicroServicesExampleDriver`, we use the `q` command. + +\note Because our french dictionary module has a link dependency on the +dictionary service module from Example 2, this module is automatically loaded +by the operating system loader. Unloading it will only succeed if there are +no other dependent modules like our french dictionary module currently loaded. + +Next: \ref MicroServices_Example3 + +Previous: \ref MicroServices_Example2 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example3.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example3.md new file mode 100644 index 0000000000..2c225c7ecf --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example3.md @@ -0,0 +1,58 @@ +Example 3 - Dictionary Client Module {#MicroServices_Example3} +==================================== + +This example creates a module that is a client of the dictionary service +implemented in \ref MicroServices_Example2 "Example 2". In the following +source code, our module uses its module context to query for a dictionary +service. Our client module uses the first dictionary service it finds and +if none are found it simply prints a message saying so and stops. Using +a service is the same as using any C++ class. The source code for our +module is as follows in a file called `dictionaryclient2/Activator.cpp`: + +\snippet dictionaryclient/Activator.cpp Activator + +Note that we do not need to unget or release the service in the Unload() +method, because the C++ Micro Services library will automatically do so +for us. + +Since we are using the `IDictionaryService` interface defined in Example 1, +we must link our module to the `dictionaryservice` module: + +\include dictionaryclient/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient` command to load +our dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +This example client is simple enough and, in fact, is too simple. What would +happen if the dictionary service were to unregister suddenly? Our client would +abort with a segmentation fault due to a null pointer access when trying to use +the service object. This dynamic service availability issue is a central tenent +of the service model. As a result, we must make our client more robust in dealing +with such situations. In \ref MicroServices_Example4 "Example 4", we explore a +slightly more complicated dictionary client that dynamically monitors service +availability. + +Next: \ref MicroServices_Example4 + +Previous: \ref MicroServices_Example2 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example4.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example4.md new file mode 100644 index 0000000000..a43e7dc970 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example4.md @@ -0,0 +1,66 @@ +Example 4 - Robust Dictionary Client Module {#MicroServices_Example4} +=========================================== + +In \ref MicroServices_Example3 "Example 3", we create a simple client module +for our dictionary service. The problem with that client was that it did not +monitor the dynamic availability of the dictionary service, thus an error +would occur if the dictionary service disappeared while the client was using it. +In this example we create a client for the dictionary service that monitors +the dynamic availability of the dictionary service. The result is a more robust +client. + +The functionality of the new dictionary client is essentially the same as the +old client, it reads words from standard input and checks for their existence +in the dictionary service. Our module uses its module context to register itself +as a service event listener; monitoring service events allows the module to +monitor the dynamic availability of the dictionary service. Our client uses the +first dictionary service it finds. The source code for our module is as follows +in a file called `Activator.cpp`: + +\snippet dictionaryclient2/Activator.cpp Activator + +The client listens for service events indicating the arrival or departure of +dictionary services. If a new dictionary service arrives, the module will start +using that service if and only if it currently does not have a dictionary service. +If an existing dictionary service disappears, the module will check to see if the +disappearing service is the one it is using; if it is it stops using it and tries +to query for another dictionary service, otherwise it ignores the event. + +As in Example 3, we must link our module to the `dictionaryservice` module: + +\include dictionaryclient2/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient2` command to load +our robust dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient2 +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +Since this client monitors the dynamic availability of the dictionary service, +it is robust in the face of sudden departures of the the dictionary service. +Further, when a dictionary service arrives, it automatically gets the service if +it needs it and continues to function. These capabilities are a little difficult +to demonstrate since we are using a simple single-threaded approach, but in a +multi-threaded or GUI-oriented application this robustness is very useful. + +Next: \ref MicroServices_Example5 + +Previous: \ref MicroServices_Example3 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example5.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example5.md new file mode 100644 index 0000000000..419fbad5bb --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example5.md @@ -0,0 +1,61 @@ +Example 5 - Service Tracker Dictionary Client Module {#MicroServices_Example5} +==================================================== + +In \ref MicroServices_Example4 "Example 4", we created a more robust client bundle +for our dictionary service. Due to the complexity of dealing with dynamic service +availability, even that client may not sufficiently address all situations. To +deal with this complexity the C++ Micro Services library provides the `ServiceTracker` +utility class. In this example we create a client for the dictionary service that +uses the `ServiceTracker` class to monitor the dynamic availability of the dictionary +service, resulting in an even more robust client. + +The functionality of the new dictionary client is essentially the same as the one +from Example 4. Our module uses its module context to create a `ServiceTracker` +instance to track the dynamic availability of the dictionary service on our behalf. +Our client uses the dictionary service returned by the `ServiceTracker`, which is +selected based on a ranking algorithm defined by the C++ Micro Services library. +The source code for our modules is as follows in a file called +`dictionaryclient3/Activator.cpp`: + +\snippet dictionaryclient3/Activator.cpp Activator + +Since this client uses the `ServiceTracker` utility class, it will automatically +monitor the dynamic availability of the dictionary service. Again, we must link +our module to the `dictionaryservice` module: + +\include dictionaryclient3/CMakeLists.txt + +After running the `CppMicroServicesExampleDriver` executable, and loading the event +listener module, we can use the `l dictionaryclient3` command to load +our robust dictionary client module: + +\verbatim +CppMicroServices-debug> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l dictionaryclient3 +Ex1: Service of type IDictionaryService/1.0 registered. +Enter a blank line to exit. +Enter word: +\endverbatim + +The above command loads the module and its dependencies (the `dictionaryservice` +module) in a single step. When we load the module, it will use the main thread to +prompt us for words. Enter one word at a time to check the words and enter a +blank line to stop checking words. To reload the module, we must use the `s` +command to get the module identifier number for the module and first use the +`u ` command to unload the module, then the `l ` command to re-load it. +To test the dictionary service, enter any of the words in the dictionary +(e.g., "welcome", "to", "the", "micro", "services", "tutorial") or any word not +in the dictionary. + +Since this client monitors the dynamic availability of the dictionary service, +it is robust in the face of sudden departures of the the dictionary service. +Further, when a dictionary service arrives, it automatically gets the service if +it needs it and continues to function. These capabilities are a little difficult +to demonstrate since we are using a simple single-threaded approach, but in a +multi-threaded or GUI-oriented application this robustness is very useful. + +Next: \ref MicroServices_Example6 + +Previous: \ref MicroServices_Example4 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example6.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example6.md new file mode 100644 index 0000000000..66559e8931 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example6.md @@ -0,0 +1,123 @@ +Example 6 - Spell Checker Service Module {#MicroServices_Example6} +======================================== + +In this example, we complicate things further by defining a new service that +uses an arbitrary number of dictionary services to perform its function. More +precisely, we define a spell checker service which will aggregate all dictionary +services and provide another service that allows us to spell check passages +using our underlying dictionary services to verify the spelling of words. Our +module will only provide the spell checker service if there are at least two +dictionary services available. First, we will start by defining the spell checker +service interface in a file called `spellcheckservice/ISpellCheckService.h`: + +\snippet spellcheckservice/ISpellCheckService.h service + +The service interface is quite simple, with only one method that needs to be +implemented. Because we provide an empty out-of-line destructor (defined in the +file `ISpellCheckService.cpp`) we must export the service interface by using the +module specific `SPELLCHECKSERVICE_EXPORT` macro. + +In the following source code, the module needs to create a complete list of all +dictionary services; this is somewhat tricky and must be done carefully if done +manually via service event listners. Our module makes use of the `ServiceTracker` +and `ServiceTrackerCustomizer` classes to robustly react to service events related +to dictionary services. The module activator of our module now additionally implements +the `ServiceTrackerCustomizer` class to be automatically notified of arriving, departing, +or modified dictionary services. In case of a newly added dictionary service, our +`ServiceTrackerCustomizer::AddingService()` implementation checks if a spell checker +service was already registered and if not registers a new `ISpellCheckService` instance +if at lead two dictionary services are available. +If the number of dictionary services drops below two, our `ServiceTrackerCustomizer` +implementation un-registers the previously registered spell checker service instance. +These actions must be performed in a synchronized manner to avoid interference from +service events originating from different threads. The implementation of our module +activator is done in a file called `spellcheckservice/Activator.cpp`: + +\snippet spellcheckservice/Activator.cpp Activator + +Note that we do not need to unregister the service in stop() method, because the +C++ Micro Services library will automatically do so for us. The spell checker service +that we have implemented is very simple; it simply parses a given passage into words +and then loops through all available dictionary services for each word until it +determines that the word is correct. Any incorrect words are added to an error list +that will be returned to the caller. This solution is not optimal and is only intended +for educational purposes. + +\note In this example, the service interface and implementation are both +contained in one module which exports the interface class. However, service +implementations almost never need to be exported and in many use cases +it is beneficial to provide the service interface and its implementation(s) +in separate modules. In such a scenario, clients of a service will only +have a link-time dependency on the shared library providing the service interface +(because of the out-of-line destructor) but not on any modules containing +service implementations. This often leads to modules which do not export +any symbols at all and hence need to be loaded into the running process +manually or by using the \ref MicroServices_AutoLoading "auto-loading mechanism". + +\note Due to the link dependency of our module to the module containing the +dictionary service interface as well as a default implementation for it, there +might be at least one dictionary service registered when our module is +loaded, depending on your linker settings (e.g. on Windows, the linker usually +by default optimizes the link dependency away since our module does not actually +use any symbols from the dictionaryservice module. On Linux however, the link +dependency is kept by default.) To observe the dynamic registration and +un-registration of our spell checker service, we require the availability of +at least two dictionary services. + +For an introduction how to compile our source code, see \ref MicroServices_Example1. + +After running the `CppMicroServicesExampleDriver` program we should make sure that the +module from Example 1 is active. We can use the `s` shell command to get +a list of all modules, their state, and their module identifier number. +If the Example 1 module is not active, we should load the module using the +load command and the module's identifier number or name that is displayed +by the `s` command. Now we can load the spell checker service module by +entering the `l spellcheckservice` command which will also trigger the loading +of the dictionaryservice module containing the english dictionary: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l eventlistener +Starting to listen for service events. +> l spellcheckservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | frenchdictionary | - + - | spellcheckclient | - + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | Spell Check Service | LOADED +> +\endverbatim + +To trigger the registration of the spell checker service from our module, we +load the frenchdictionary using the `l frenchdictionary` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its spell checker service: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l frenchdictionary +Ex1: Service of type IDictionaryService/1.0 registered. +Ex1: Service of type ISpellCheckService/1.0 registered. +> +\endverbatim + +We can experiment with our spell checker service's dynamic availability by stopping +the french dictionary service; when the service is stopped, +the eventlistener module will print that our module is no longer offering its +spell checker service. Likewise, when the french dictionary service comes back, so will +our spell checker service. We create a client for our spell checker service in +\ref MicroServices_Example7 "Example 7". To exit the `CppMicroServicesExampleDriver` program, we +use the `q` command. + +Next: \ref MicroServices_Example7 + +Previous: \ref MicroServices_Example5 diff --git a/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example7.md b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example7.md new file mode 100644 index 0000000000..8bcdc5e997 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/examples/MicroServices_Example7.md @@ -0,0 +1,73 @@ +Example 7 - Spell Checker Client Module {#MicroServices_Example7} +======================================= + +In this example we create a client for the spell checker service we implemented +in \ref MicroServices_Example6 "Example 6". This client monitors the dynamic +availability of the spell checker service using the Service Tracker and is very +similar in structure to the dictionary client we implemented in +\ref MicroServices_Example5 "Example 5". The functionality of the spell checker +client reads passages from standard input and spell checks them using the spell +checker service. Our module uses its module context to create a `ServiceTracker` +object to monitor spell checker services. The source code for our module is as +follows in a file called `spellcheckclient/Activator.cpp`: + +\snippet spellcheckclient/Activator.cpp Activator + +After running the `CppMicroServicesExampleDriver` program use the `s` command to make sure that +only the modules from Example 2, Example 2b, and Example 6 are loaded; use the +load (`l`) and un-load (`u`) commands as appropriate to load and un-load the +various tutorial modules, respectively. Now we can load our spell checker client +module by entering `l spellcheckclient`: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l +Starting to listen for service events. +> l spellcheckservice +Ex1: Service of type IDictionaryService/1.0 registered. +> s +Id | Name | Status +----------------------------------- + - | dictionaryclient | - + - | dictionaryclient2 | - + - | dictionaryclient3 | - + - | frenchdictionary | - + - | spellcheckclient | - + 1 | CppMicroServices | LOADED + 2 | Event Listener | LOADED + 3 | Dictionary Service | LOADED + 4 | Spell Check Service | LOADED +> +\endverbatim + +To trigger the registration of the spell checker service from our module, we +load the frenchdictionary using the `l frenchdictionary` command. If the module from +\ref MicroServices_Example1 "Example 1" is still active, +then we should see it print out the details of the service event it receives +when our new module registers its spell checker service: + +\verbatim +CppMicroServices-build> bin/CppMicroServicesExampleDriver +> l spellcheckservice +> l frenchdictionary +> l spellcheckclient +Enter a blank line to exit. +Enter passage: +\endverbatim + +When we start the module, it will use the main thread to prompt us for passages; a +passage is a collection or words separate by spaces, commas, periods, exclamation +points, question marks, colons, or semi-colons. Enter a passage and press the enter +key to spell check the passage or enter a blank line to stop spell checking passages. +To restart the module, we must use the command `s` command to get the module identifier +number for the module and first use the `u` command to un-load the module, then the +`l` command to re-load it. + +Since this client uses the Service Tracker to monitor the dynamic availability of the +spell checker service, it is robust in the scenario where the spell checker service +suddenly departs. Further, when a spell checker service arrives, it automatically gets +the service if it needs it and continues to function. These capabilities are a little +difficult to demonstrate since we are using a simple single-threaded approach, but in +a multi-threaded or GUI-oriented application this robustness is very useful. + +Previous: \ref MicroServices_Example6 diff --git a/Core/Code/CppMicroServices/documentation/doxygen/footer.html b/Core/CppMicroServices/documentation/doxygen/footer.html similarity index 64% rename from Core/Code/CppMicroServices/documentation/doxygen/footer.html rename to Core/CppMicroServices/documentation/doxygen/footer.html index 38c8204a29..ea6b6dac83 100644 --- a/Core/Code/CppMicroServices/documentation/doxygen/footer.html +++ b/Core/CppMicroServices/documentation/doxygen/footer.html @@ -1,9 +1,4 @@ - - -
- - + diff --git a/Core/CppMicroServices/documentation/doxygen/header.html b/Core/CppMicroServices/documentation/doxygen/header.html new file mode 100644 index 0000000000..cc5afab151 --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/header.html @@ -0,0 +1,23 @@ +--- +layout: default +title: $title +--- + + + + $projectname: $title + $title + + + + + $treeview + $search + $mathjax + + + $extrastylesheet + + + +
diff --git a/Core/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md b/Core/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md new file mode 100644 index 0000000000..8319e6bd7a --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md @@ -0,0 +1,59 @@ +Build Instructions {#BuildInstructions} +================== + +The C++ Micro Services library provides [CMake][cmake] build scripts which allow the generation of +platform and IDE specific project files. + +The library should compile on many different platforms. Below is a list of tested compiler/OS combinations: + + - GCC 4.5 (Ubuntu 11.04 and MacOS X 10.6) + - GCC 4.7 (Ubuntu 12.10) + - Visual Studio 2008, 2010, and 2012 + - Clang 3.0 (Ubuntu 12.10 and MacOS X 10.6) + + +Prerequisites +------------- + +- [CMake][cmake] 2.8 (Visual Studio 2010 and 2012 users should use the latest CMake version available) + + +Configuring the Build +--------------------- + +When building the C++ Micro Services library, you have a few configuration options at hand. + +### General build options + +- **CMAKE_INSTALL_PREFIX** + The installation path. +- **US_BUILD_SHARED_LIBS** + Specify if the library should be build shared or static. See \ref MicroServices_StaticModules + for detailed information about static CppMicroServices modules. +- **US_BUILD_TESTING** + Build unit tests and code snippets. +- **US_ENABLE_AUTOLOADING_SUPPORT** + Enable auto-loading of modules located in special sup-directories. See \ref MicroServices_AutoLoading + for detailed information about this feature. +- **US_ENABLE_THREADING_SUPPORT** + Enable the use of synchronization primitives (atomics and pthread mutexes or Windows primitives) + to make the API thread-safe. If you are application is not multi-threaded, turn this option OFF + to get maximum performance. +- **US_USE_C++11 (advanced)** + Enable the usage of C++11 constructs. +- **US_ENABLE_RESOURCE_COMPRESSION (advanced)** + Enable compression of embedded resources. See \ref MicroServices_Resources for detailed information + about the resource system. + +### Customizing naming conventions + +- **US_NAMESPACE** + The default namespace is `us` but you may override this at will. +- **US_HEADER_PREFIX** + By default, all public headers have a "us" prefix. You may specify an arbitrary prefix to match your + naming conventions. + +The above options are mainly useful when embedding the C++ Micro Services source code in your own library and +you want to make it look like native source code. + +[cmake]: http://www.cmake.org diff --git a/Core/CppMicroServices/documentation/doxygen/standalone/MicroServices_GettingStarted.md b/Core/CppMicroServices/documentation/doxygen/standalone/MicroServices_GettingStarted.md new file mode 100644 index 0000000000..fec5a1105c --- /dev/null +++ b/Core/CppMicroServices/documentation/doxygen/standalone/MicroServices_GettingStarted.md @@ -0,0 +1,49 @@ +Getting Started {#MicroServices_GettingStarted} +=============== + +Projects which want to make use of the capabilities provided by the C++ Micro Services +library need to set-up the correct include paths and link dependencies. Further, each +executable or shared library which needs a ModuleContext instance must contain specific +initialization code. + +The C++ Micro Services library provides \ref MicroServicesCMake "CMake utility functions" +for CMake based projects but there are no restrictions on the type of build system used +for a project. + +CMake based projects +-------------------- + +To easily set-up include paths and linker dependencies, use the common `find_package` +mechanism provided by CMake: + +\dontinclude examples/CMakeLists.txt +\skip project +\until include_directories + +The CMake code above sets up a basic project (called CppMicroServicesExamples) and tries +to find the CppMicroServices package and subsequently to set the necessary include +directories. Building a shared library might then look like this: + +\dontinclude examples/dictionaryservice/CMakeLists.txt +\until target_link + +The call to `#usFunctionGenerateModuleInit` generates the proper module initialization +code and provides access to the module specific ModuleContext instance. + +Makefile based projects +----------------------- + +The following Makefile is located at examples/makefile/Makefile and demonstrates a minimal +build script: + +\include makefile/Makefile + +The variable `CppMicroServices_ROOT` is an environment variable and must be set to the +CppMicroServices installation directory prior to invoking `make`. The module initialization +code for the `libmodule.so` shared library is generated by using the `#US_INITIALIZE_MODULE` +pre-processor macro at the end of the `module.cpp` source file (any source file compiled +into the module would do): + +\dontinclude makefile/module.cpp +\skip usModuleInitialization +\until US_INITIALIZE_MODULE diff --git a/Core/CppMicroServices/documentation/snippets/CMakeLists.txt b/Core/CppMicroServices/documentation/snippets/CMakeLists.txt new file mode 100644 index 0000000000..5540734bb9 --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/CMakeLists.txt @@ -0,0 +1,4 @@ + +include_directories(${US_INCLUDE_DIRS}) + +usFunctionCompileSnippets("${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-activator/main.cpp similarity index 100% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-activator/main.cpp diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp similarity index 90% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp index b46013fe89..a793f3b343 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp @@ -1,28 +1,28 @@ #include //! [GetModuleContext] #include #include #include US_USE_NAMESPACE void RetrieveModuleContext() { ModuleContext* context = GetModuleContext(); Module* module = context->GetModule(); std::cout << "Module name: " << module->GetName() << " [id: " << module->GetModuleId() << "]\n"; } //! [GetModuleContext] //! [InitializeModule] #include -US_INITIALIZE_MODULE("My Module", "mylibname", "", "1.0.0") +US_INITIALIZE_MODULE("My Module", "mylibname") //! [InitializeModule] int main(int /*argc*/, char* /*argv*/[]) { RetrieveModuleContext(); return 0; } diff --git a/Core/CppMicroServices/documentation/snippets/uServices-registration/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-registration/main.cpp new file mode 100644 index 0000000000..be9666e635 --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/uServices-registration/main.cpp @@ -0,0 +1,119 @@ +#include +#include +#include +#include + +US_USE_NAMESPACE + + +struct InterfaceA { virtual ~InterfaceA() {} }; +struct InterfaceB { virtual ~InterfaceB() {} }; +struct InterfaceC { virtual ~InterfaceC() {} }; + +US_DECLARE_SERVICE_INTERFACE(InterfaceA, "org.cppmicroservices.snippet.InterfaceA") +US_DECLARE_SERVICE_INTERFACE(InterfaceB, "org.cppmicroservices.snippet.InterfaceB") +US_DECLARE_SERVICE_INTERFACE(InterfaceC, "org.cppmicroservices.snippet.InterfaceC") + +//! [1-1] +class MyService : public InterfaceA +{}; +//! [1-1] + +//! [2-1] +class MyService2 : public InterfaceA, public InterfaceB +{}; +//! [2-1] + +class MyActivator : public ModuleActivator +{ + +public: + + void Load(ModuleContext* context) + { + Register1(context); + Register2(context); + RegisterFactory1(context); + RegisterFactory2(context); + } + + void Register1(ModuleContext* context) + { +//! [1-2] +MyService* myService = new MyService; +context->RegisterService(myService); +//! [1-2] + } + + void Register2(ModuleContext* context) + { +//! [2-2] +MyService2* myService = new MyService2; +context->RegisterService(myService); +//! [2-2] + } + + void RegisterFactory1(ModuleContext* context) + { +//! [f1] +class MyServiceFactory : public ServiceFactory +{ + virtual InterfaceMap GetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/) + { + MyService* myService = new MyService; + return MakeInterfaceMap(myService); + } + + virtual void UngetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/, + const InterfaceMap& service) + { + delete ExtractInterface(service); + } +}; + +MyServiceFactory* myServiceFactory = new MyServiceFactory; +context->RegisterService(myServiceFactory); +//! [f1] + } + + void RegisterFactory2(ModuleContext* context) + { +//! [f2] +class MyServiceFactory : public ServiceFactory +{ + virtual InterfaceMap GetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/) + { + MyService2* myService = new MyService2; + return MakeInterfaceMap(myService); + } + + virtual void UngetService(Module* /*module*/, const ServiceRegistrationBase& /*registration*/, + const InterfaceMap& service) + { + delete ExtractInterface(service); + } +}; + +MyServiceFactory* myServiceFactory = new MyServiceFactory; +context->RegisterService(static_cast(myServiceFactory)); +//! [f2] +// In the RegisterService call above, we could remove the static_cast because local types +// are not considered in template argument type deduction and hence the compiler choose +// the correct RegisterService(ServiceFactory*) overload. However, local types are +// usually the exception and using a non-local type for the service factory would make the +// compiler choose RegisterService(Impl*) instead, unless we use the static_cast. + } + + + void Unload(ModuleContext* /*context*/) + { /* cleanup */ } + +}; + +US_EXPORT_MODULE_ACTIVATOR(mylibname, MyActivator) + +int main(int /*argc*/, char* /*argv*/[]) +{ + MyActivator ma; + return 0; +} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-resources/main.cpp similarity index 95% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-resources/main.cpp index 78674294d6..474c344374 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-resources/main.cpp @@ -1,88 +1,86 @@ #include #include #include #include #include #include US_USE_NAMESPACE void resourceExample() { //! [1] // Get this module's Module object Module* module = GetModuleContext()->GetModule(); ModuleResource resource = module->GetResource("config.properties"); if (resource.IsValid()) { // Create a ModuleResourceStream object ModuleResourceStream resourceStream(resource); // Read the contents line by line std::string line; while (std::getline(resourceStream, line)) { // Process the content std::cout << line << std::endl; } } else { // Error handling } //! [1] } void parseComponentDefinition(std::istream&) { } void extenderPattern() { //! [2] // Get all loaded modules std::vector modules; ModuleRegistry::GetLoadedModules(modules); // Check if a module defines a "service-component" property // and use its value to retrieve an embedded resource containing // a component description. for(std::size_t i = 0; i < modules.size(); ++i) { Module* const module = modules[i]; - std::string componentPath = module->GetProperty("service-component"); + std::string componentPath = module->GetProperty("service-component").ToString(); if (!componentPath.empty()) { ModuleResource componentResource = module->GetResource(componentPath); if (!componentResource.IsValid() || componentResource.IsDir()) continue; // Create a std::istream compatible object and parse the // component description. ModuleResourceStream resStream(componentResource); parseComponentDefinition(resStream); } } //! [2] } int main(int /*argc*/, char* /*argv*/[]) { //! [0] ModuleContext* moduleContext = GetModuleContext(); Module* module = moduleContext->GetModule(); // List all XML files in the config directory std::vector xmlFiles = module->FindResources("config", "*.xml", false); // Find the resource named vertex_shader.txt starting at the root directory std::vector shaders = module->FindResources("", "vertex_shader.txt", true); //! [0] return 0; } -#ifdef US_BUILD_SHARED_LIBS #include -US_INITIALIZE_MODULE("uServices-snippet-resources", "", "", "1.0.0") -#endif +US_INITIALIZE_EXECUTABLE("uServices-snippet-resources") diff --git a/Core/CppMicroServices/documentation/snippets/uServices-servicetracker/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-servicetracker/main.cpp new file mode 100644 index 0000000000..0c1bc68bef --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/uServices-servicetracker/main.cpp @@ -0,0 +1,110 @@ +#include +#include + +US_USE_NAMESPACE + +struct IFooService {}; + +US_DECLARE_SERVICE_INTERFACE(IFooService, "org.cppmicroservices.snippets.IFooService") + +///! [tt] +struct MyTrackedClass { /* ... */ }; +//! [tt] + +//! [ttt] +struct MyTrackedClassTraits : public TrackedTypeTraitsBase +{ + static bool IsValid(const TrackedType&) + { + // Dummy implementation + return true; + } + + static void Dispose(TrackedType&) + {} + + static TrackedType DefaultValue() + { + return TrackedType(); + } +}; +//! [ttt] + +//! [customizer] +struct MyTrackingCustomizer : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass AddingService(const ServiceReferenceT&) + { + return MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass) + { + } +}; +//! [customizer] + +struct MyTrackingPointerCustomizer : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass* AddingService(const ServiceReferenceT&) + { + return new MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass*) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass*) + { + } +}; + +// For compilation test purposes only +struct MyTrackingCustomizerVoid : public ServiceTrackerCustomizer +{ + virtual MyTrackedClass AddingService(const ServiceReferenceT&) + { + return MyTrackedClass(); + } + + virtual void ModifiedService(const ServiceReferenceT&, MyTrackedClass) + { + } + + virtual void RemovedService(const ServiceReferenceT&, MyTrackedClass) + { + } +}; + +int main(int /*argc*/, char* /*argv*/[]) +{ + { +//! [tracker] +MyTrackingCustomizer myCustomizer; +ServiceTracker tracker(GetModuleContext(), &myCustomizer); +//! [tracker] + } + + { +//! [tracker2] +MyTrackingPointerCustomizer myCustomizer; +ServiceTracker > tracker(GetModuleContext(), &myCustomizer); +//! [tracker2] + } + + // For compilation test purposes only + MyTrackingCustomizerVoid myCustomizer2; + ServiceTracker tracker2(GetModuleContext(), &myCustomizer2); + ServiceTracker > tracker3(GetModuleContext()); + + return 0; +} + +#include + +US_INITIALIZE_EXECUTABLE("uServices-modulecontext") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp similarity index 94% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp index 7b7e777626..9380cb316d 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp @@ -1,80 +1,80 @@ #include "SingletonOne.h" #include "SingletonTwo.h" #include #include #include #include US_USE_NAMESPACE //![s1] SingletonOne& SingletonOne::GetInstance() { static SingletonOne instance; return instance; } //![s1] SingletonOne::SingletonOne() : a(1) { } //![s1d] SingletonOne::~SingletonOne() { std::cout << "SingletonTwo::b = " << SingletonTwo::GetInstance().b << std::endl; } //![s1d] //![ss1gi] SingletonOneService* SingletonOneService::GetInstance() { - static ServiceReference serviceRef; + static ServiceReference serviceRef; static ModuleContext* context = GetModuleContext(); if (!serviceRef) { // This is either the first time GetInstance() was called, // or a SingletonOneService instance has not yet been registered. serviceRef = context->GetServiceReference(); } if (serviceRef) { // We have a valid service reference. It always points to the service // with the lowest id (usually the one which was registered first). // This still might return a null pointer, if all SingletonOneService // instances have been unregistered (during unloading of the library, // for example). - return context->GetService(serviceRef); + return context->GetService(serviceRef); } else { // No SingletonOneService instance was registered yet. return 0; } } //![ss1gi] SingletonOneService::SingletonOneService() : a(1) { SingletonTwoService* singletonTwoService = SingletonTwoService::GetInstance(); assert(singletonTwoService != 0); std::cout << "SingletonTwoService::b = " << singletonTwoService->b << std::endl; } //![ss1d] SingletonOneService::~SingletonOneService() { SingletonTwoService* singletonTwoService = SingletonTwoService::GetInstance(); // The module activator must ensure that a SingletonTwoService instance is // available during destruction of a SingletonOneService instance. assert(singletonTwoService != 0); std::cout << "SingletonTwoService::b = " << singletonTwoService->b << std::endl; } //![ss1d] diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h similarity index 94% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h index a8aa153e56..62dbf89270 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h @@ -1,66 +1,64 @@ #ifndef SINGLETONONE_H #define SINGLETONONE_H #include #include #include #include -#include US_BASECLASS_HEADER - //![s1] class SingletonOne { public: static SingletonOne& GetInstance(); // Just some member int a; private: SingletonOne(); ~SingletonOne(); // Disable copy constructor and assignment operator. SingletonOne(const SingletonOne&); SingletonOne& operator=(const SingletonOne&); }; //![s1] class SingletonTwoService; //![ss1] -class SingletonOneService : public US_BASECLASS_NAME +class SingletonOneService { public: // This will return a SingletonOneService instance with the // lowest service id at the time this method was called the first // time and returned a non-null value (which is usually the instance // which was registered first). A null-pointer is returned if no // instance was registered yet. static SingletonOneService* GetInstance(); int a; private: // Only our module activator class should be able to instantiate // a SingletonOneService object. friend class MyActivator; SingletonOneService(); ~SingletonOneService(); // Disable copy constructor and assignment operator. SingletonOneService(const SingletonOneService&); SingletonOneService& operator=(const SingletonOneService&); }; US_DECLARE_SERVICE_INTERFACE(SingletonOneService, "org.cppmicroservices.snippet.SingletonOneService") //![ss1] #endif // SINGLETONONE_H diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp similarity index 93% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp index 84aeab43d5..db18f6ae01 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp @@ -1,64 +1,64 @@ #include "SingletonTwo.h" #include "SingletonOne.h" #include #include #include US_USE_NAMESPACE SingletonTwo& SingletonTwo::GetInstance() { static SingletonTwo instance; return instance; } SingletonTwo::SingletonTwo() : b(2) { std::cout << "Constructing SingletonTwo" << std::endl; } SingletonTwo::~SingletonTwo() { std::cout << "Deleting SingletonTwo" << std::endl; std::cout << "SingletonOne::a = " << SingletonOne::GetInstance().a << std::endl; } SingletonTwoService* SingletonTwoService::GetInstance() { - static ServiceReference serviceRef; + static ServiceReference serviceRef; static ModuleContext* context = GetModuleContext(); if (!serviceRef) { // This is either the first time GetInstance() was called, // or a SingletonTwoService instance has not yet been registered. serviceRef = context->GetServiceReference(); } if (serviceRef) { // We have a valid service reference. It always points to the service // with the lowest id (usually the one which was registered first). // This still might return a null pointer, if all SingletonTwoService // instances have been unregistered (during unloading of the library, // for example). - return context->GetService(serviceRef); + return context->GetService(serviceRef); } else { // No SingletonTwoService instance was registered yet. return 0; } } SingletonTwoService::SingletonTwoService() : b(2) { std::cout << "Constructing SingletonTwoService" << std::endl; } SingletonTwoService::~SingletonTwoService() { std::cout << "Deleting SingletonTwoService" << std::endl; } diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h similarity index 91% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h index ab5444a2cc..9eb8e2b36b 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h @@ -1,49 +1,48 @@ #ifndef SINGLETONTWO_H #define SINGLETONTWO_H #include #include -#include US_BASECLASS_HEADER class SingletonTwo { public: static SingletonTwo& GetInstance(); int b; private: SingletonTwo(); ~SingletonTwo(); // Disable copy constructor and assignment operator. SingletonTwo(const SingletonTwo&); SingletonTwo& operator=(const SingletonTwo&); }; -class SingletonTwoService : public US_BASECLASS_NAME +class SingletonTwoService { public: static SingletonTwoService* GetInstance(); int b; private: friend class MyActivator; SingletonTwoService(); ~SingletonTwoService(); // Disable copy constructor and assignment operator. SingletonTwoService(const SingletonTwoService&); SingletonTwoService& operator=(const SingletonTwoService&); }; US_DECLARE_SERVICE_INTERFACE(SingletonTwoService, "org.cppmicroservices.snippet.SingletonTwoService") #endif // SINGLETONTWO_H diff --git a/Core/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake b/Core/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake new file mode 100644 index 0000000000..7de7f5c5ad --- /dev/null +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake @@ -0,0 +1,10 @@ + +set(snippet_src_files + main.cpp + SingletonOne.cpp + SingletonTwo.cpp +) + +usFunctionGenerateExecutableInit(snippet_src_files + IDENTIFIER "uServices_singleton" + ) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp similarity index 93% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp index 6d44cdab86..9980ee1f53 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp @@ -1,69 +1,69 @@ #include #include #include #include "SingletonOne.h" #include "SingletonTwo.h" US_USE_NAMESPACE class MyActivator : public ModuleActivator { public: //![0] void Load(ModuleContext* context) { // The Load() method of the module activator is called during static // initialization time of the shared library. // First create and register a SingletonTwoService instance. m_SingletonTwo = new SingletonTwoService; m_SingletonTwoReg = context->RegisterService(m_SingletonTwo); // Now the SingletonOneService constructor will get a valid // SingletonTwoService instance. m_SingletonOne = new SingletonOneService; m_SingletonOneReg = context->RegisterService(m_SingletonOne); } //![0] //![1] void Unload(ModuleContext* /*context*/) { // Services are automatically unregistered during unloading of // the shared library after the call to Unload(ModuleContext*) // has returned. // Since SingletonOneService needs a non-null SingletonTwoService // instance in its destructor, we explicitly unregister and delete the // SingletonOneService instance here. This way, the SingletonOneService // destructor will still get a valid SingletonTwoService instance. m_SingletonOneReg.Unregister(); delete m_SingletonOne; // For singletonTwoService, we could rely on the automatic unregistering // by the service registry and on automatic deletion if you used // smart pointer reference counting. You must not delete service instances // in this method without unregistering them first. m_SingletonTwoReg.Unregister(); delete m_SingletonTwo; } //![1] private: SingletonOneService* m_SingletonOne; SingletonTwoService* m_SingletonTwo; - ServiceRegistration m_SingletonOneReg; - ServiceRegistration m_SingletonTwoReg; + ServiceRegistration m_SingletonOneReg; + ServiceRegistration m_SingletonTwoReg; }; US_EXPORT_MODULE_ACTIVATOR(uServices_singleton, MyActivator) int main() { } diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp similarity index 94% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp index f63af3272a..2984c93702 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp @@ -1,40 +1,39 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include US_USE_NAMESPACE struct MyStaticModuleActivator : public ModuleActivator { void Load(ModuleContext* /*context*/) { std::cout << "Hello from a static module." << std::endl; } void Unload(ModuleContext* /*context*/) {} }; US_EXPORT_MODULE_ACTIVATOR(MyStaticModule, MyStaticModuleActivator) -US_INITIALIZE_MODULE("My Static Module", "MyStaticModule", "", "1.0.0") - +US_INITIALIZE_MODULE("My Static Module", "MyStaticModule") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake similarity index 100% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake rename to Core/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp similarity index 91% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp rename to Core/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp index 13364d4d34..e78d3a64c4 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp +++ b/Core/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp @@ -1,36 +1,34 @@ #include US_USE_NAMESPACE //! [ImportStaticModuleIntoLib] #include US_IMPORT_MODULE(MyStaticModule) US_LOAD_IMPORTED_MODULES(HostingModule, MyStaticModule) //! [ImportStaticModuleIntoLib] // This is just for illustration purposes in code snippets extern "C" ModuleActivator* _us_module_activator_instance_MyStaticModule1() { return NULL; } extern "C" ModuleActivator* _us_module_activator_instance_MyStaticModule2() { return NULL; } extern "C" ModuleActivator* _us_init_resources_MyStaticModule2() { return NULL; } //! [ImportStaticModuleIntoMain] #include US_IMPORT_MODULE(MyStaticModule1) US_IMPORT_MODULE(MyStaticModule2) US_IMPORT_MODULE_RESOURCES(MyStaticModule2) US_LOAD_IMPORTED_MODULES_INTO_MAIN(MyStaticModule1 MyStaticModule2) //! [ImportStaticModuleIntoMain] int main(int /*argc*/, char* /*argv*/[]) { return 0; } //! [InitializeExecutable] -#ifdef US_BUILD_SHARED_LIBS #include -US_INITIALIZE_MODULE("MyExecutable", "", "", "1.0.0") -#endif +US_INITIALIZE_EXECUTABLE("MyExecutable") //! [InitializeExecutable] diff --git a/Core/CppMicroServices/examples/CMakeLists.txt b/Core/CppMicroServices/examples/CMakeLists.txt new file mode 100644 index 0000000000..745bd869c3 --- /dev/null +++ b/Core/CppMicroServices/examples/CMakeLists.txt @@ -0,0 +1,137 @@ +project(CppMicroServicesExamples) + +cmake_minimum_required(VERSION 2.8) + +find_package(CppMicroServices NO_MODULE REQUIRED) + +include_directories(${CppMicroServices_INCLUDE_DIRS}) + +#----------------------------------------------------------------------------- +# Set C/CXX flags +#----------------------------------------------------------------------------- + +if(${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CppMicroServices_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${CppMicroServices_CXX_FLAGS_RELEASE}") + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${CppMicroServices_CXX_FLAGS_DEBUG}") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CppMicroServices_C_FLAGS}") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${CppMicroServices_C_FLAGS_RELEASE}") + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${CppMicroServices_C_FLAGS_DEBUG}") +endif() + +#----------------------------------------------------------------------------- +# Init output directories +#----------------------------------------------------------------------------- + +set(CppMicroServicesExamples_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(CppMicroServicesExamples_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") +set(CppMicroServicesExamples_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") + +foreach(_type ARCHIVE LIBRARY RUNTIME) + if(NOT CMAKE_${_type}_OUTPUT_DIRECTORY) + set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CppMicroServicesExamples_${_type}_OUTPUT_DIRECTORY}) + endif() +endforeach() + + +function(CreateExample _name) + add_library(Example-${_name} SHARED ${ARGN}) + if(${_name}_DEPENDS) + foreach(_dep ${${_name}_DEPENDS}) + include_directories(${CppMicroServicesExamples_SOURCE_DIR}/${_dep}) + target_link_libraries(Example-${_name} Example-${_dep}) + endforeach() + endif() + target_link_libraries(Example-${_name} ${CppMicroServices_LIBRARIES}) + set_target_properties(Example-${_name} PROPERTIES + LABELS Examples + OUTPUT_NAME ${_name} + ) +endfunction() + +add_subdirectory(eventlistener) +add_subdirectory(dictionaryservice) +add_subdirectory(frenchdictionary) +add_subdirectory(dictionaryclient) +add_subdirectory(dictionaryclient2) +add_subdirectory(dictionaryclient3) +add_subdirectory(spellcheckservice) +add_subdirectory(spellcheckclient) +add_subdirectory(driver) + +#----------------------------------------------------------------------------- +# Test if examples compile against an install tree and if the +# Makefile example compiles +#----------------------------------------------------------------------------- + +if(US_BUILD_TESTING) + enable_testing() + + set(_example_tests ) + + set(_install_dir "${CppMicroServices_BINARY_DIR}/install_test/${CMAKE_INSTALL_PREFIX}") + + add_test(NAME usInstallCleanTest + COMMAND ${CMAKE_COMMAND} -E remove_directory "${_install_dir}") + + add_test(NAME usInstallTest + WORKING_DIRECTORY ${CppMicroServices_BINARY_DIR} + COMMAND ${CMAKE_COMMAND} --build ${CppMicroServices_BINARY_DIR} --target install) + set_tests_properties(usInstallTest PROPERTIES + ENVIRONMENT "DESTDIR=${CppMicroServices_BINARY_DIR}/install_test" + DEPENDS usInstallCleanTest) + + set(_examples_binary_dir "${CppMicroServices_BINARY_DIR}/examples_build") + + add_test(NAME usExamplesCleanTest + COMMAND ${CMAKE_COMMAND} -E remove_directory "${_examples_binary_dir}") + + add_test(NAME usExamplesCreateDirTest + COMMAND ${CMAKE_COMMAND} -E make_directory "${_examples_binary_dir}") + set_tests_properties(usExamplesCreateDirTest PROPERTIES + DEPENDS usExamplesCleanTest) + + add_test(NAME usExamplesConfigureTest + WORKING_DIRECTORY ${_examples_binary_dir} + COMMAND ${CMAKE_COMMAND} + -G ${CMAKE_GENERATOR} + -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} + "-DCppMicroServices_DIR:PATH=${_install_dir}/${CONFIG_CMAKE_DIR}" + "${CMAKE_CURRENT_LIST_DIR}") + set_tests_properties(usExamplesConfigureTest PROPERTIES + DEPENDS "usInstallTest;usExamplesCreateDirTest") + + add_test(NAME usExamplesBuildTest + WORKING_DIRECTORY ${_examples_binary_dir} + COMMAND ${CMAKE_COMMAND} --build .) + set_tests_properties(usExamplesBuildTest PROPERTIES + DEPENDS usExamplesConfigureTest) + + list(APPEND _example_tests usInstallCleanTest usInstallTest usExamplesCleanTest + usExamplesCreateDirTest usExamplesConfigureTest usExamplesBuildTest) + + # The makefile is Linux specific, so only try to build the Makefile example + # if we are on a proper system + if(UNIX AND NOT APPLE) + find_program(MAKE_COMMAND NAMES make gmake) + find_program(CXX_COMMAND NAMES g++) + mark_as_advanced(MAKE_COMMAND CXX_COMMAND) + if(MAKE_COMMAND AND CXX_COMMAND) + add_test(NAME usMakefileExampleCleanTest + WORKING_DIRECTORY ${CppMicroServices_SOURCE_DIR}/examples/makefile + COMMAND ${MAKE_COMMAND} clean) + add_test(NAME usMakefileExampleTest + WORKING_DIRECTORY ${CppMicroServices_SOURCE_DIR}/examples/makefile + COMMAND ${MAKE_COMMAND}) + set_tests_properties(usMakefileExampleTest PROPERTIES + DEPENDS "usMakefileExampleCleanTest;usInstallTest" + ENVIRONMENT "CppMicroServices_ROOT=${CppMicroServices_BINARY_DIR}/install_test${CMAKE_INSTALL_PREFIX};CppMicroServices_CXX_FLAGS=${CppMicroServices_CXX_FLAGS}") + list(APPEND _example_tests usMakefileExampleCleanTest usMakefileExampleTest) + endif() + endif() + + if(US_TEST_LABELS) + set_tests_properties(${_example_tests} PROPERTIES LABELS "${US_TEST_LABELS}") + endif() + +endif() diff --git a/Core/CppMicroServices/examples/dictionaryclient/Activator.cpp b/Core/CppMicroServices/examples/dictionaryclient/Activator.cpp new file mode 100644 index 0000000000..fc3d47f37d --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient/Activator.cpp @@ -0,0 +1,117 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary service to check for + * the proper spelling of a word by check for its existence in the dictionary. + * This modules uses the first service that it finds and does not monitor the + * dynamic availability of the service (i.e., it does not listen for the arrival + * or departure of dictionary services). When loading this module, the thread + * calling the Load() method is used to read words from standard input. You can + * stop checking words by entering an empty line, but to start checking words + * again you must unload and then load the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + /** + * Implements ModuleActivator::Load(). Queries for all available dictionary + * services. If none are found it simply prints a message and returns, + * otherwise it reads words from standard input and checks for their + * existence from the first dictionary that it finds. + * + * \note It is very bad practice to use the calling thread to perform a lengthy + * process like this; this is only done for the purpose of the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + // Query for all service references matching any language. + std::vector > refs = + context->GetServiceReferences("(Language=*)"); + + if (!refs.empty()) + { + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + + // First, get a dictionary service and then check + // if the word is correct. + IDictionaryService* dictionary = context->GetService(refs.front()); + if ( dictionary->CheckWord( word ) ) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + + // Unget the dictionary service. + context->UngetService(refs.front()); + } + } + else + { + std::cout << "Couldn't find any dictionary service..." << std::endl; + } + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically released. + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/dictionaryclient/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryclient/CMakeLists.txt new file mode 100644 index 0000000000..bd610a3686 --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client" + LIBRARY_NAME "dictionaryclient") + +set(dictionaryclient_DEPENDS dictionaryservice) +CreateExample(dictionaryclient ${_srcs}) diff --git a/Core/CppMicroServices/examples/dictionaryclient2/Activator.cpp b/Core/CppMicroServices/examples/dictionaryclient2/Activator.cpp new file mode 100644 index 0000000000..28d2e14276 --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient2/Activator.cpp @@ -0,0 +1,214 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary service to check for + * the proper spelling of a word by checking for its existence in the + * dictionary. This module is more complex than the module in Example 3 because + * it monitors the dynamic availability of the dictionary services. In other + * words, if the service it is using departs, then it stops using it gracefully, + * or if it needs a service and one arrives, then it starts using it + * automatically. As before, the module uses the first service that it finds and + * uses the calling thread of the Load() method to read words from standard + * input. You can stop checking words by entering an empty line, but to start + * checking words again you must unload and then load the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_dictionary(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Adds itself as a listener for service + * events, then queries for available dictionary services. If any + * dictionaries are found it gets a reference to the first one available and + * then starts its "word checking loop". If no dictionaries are found, then + * it just goes directly into its "word checking loop", but it will not be + * able to check any words until a dictionary service arrives; any arriving + * dictionary service will be automatically used by the client if a + * dictionary is not already in use. Once it has dictionary, it reads words + * from standard input and checks for their existence in the dictionary that + * it is using. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + { + // Use your favorite thread library to synchronize member + // variable access within this scope while registering + // the service listener and performing our initial + // dictionary service lookup since we + // don't want to receive service events when looking up the + // dictionary service, if one exists. + // MutexLocker lock(&m_mutex); + + // Listen for events pertaining to dictionary services. + m_context->AddServiceListener(this, &Activator::ServiceChanged, + std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=" + + us_service_interface_iid() + ")" + "(Language=*))"); + + // Query for any service references matching any language. + std::vector > refs = + context->GetServiceReferences("(Language=*)"); + + // If we found any dictionary services, then just get + // a reference to the first one so we can use it. + if (!refs.empty()) + { + m_ref = refs.front(); + m_dictionary = m_context->GetService(m_ref); + } + } + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + // If there is no dictionary, then say so. + else if (m_dictionary == NULL) + { + std::cout << "No dictionary available." << std::endl; + } + // Otherwise print whether the word is correct or not. + else if (m_dictionary->CheckWord( word )) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + } + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically released. + } + + /** + * Implements ServiceListener.serviceChanged(). Checks to see if the service + * we are using is leaving or tries to get a service if we need one. + * + * @param event the fired service event. + */ + void ServiceChanged(const ServiceEvent event) + { + // Use your favorite thread library to synchronize this + // method with the Load() method. + // MutexLocker lock(&m_mutex); + + // If a dictionary service was registered, see if we + // need one. If so, get a reference to it. + if (event.GetType() == ServiceEvent::REGISTERED) + { + if (!m_ref) + { + // Get a reference to the service object. + m_ref = event.GetServiceReference(); + m_dictionary = m_context->GetService(m_ref); + } + } + // If a dictionary service was unregistered, see if it + // was the one we were using. If so, unget the service + // and try to query to get another one. + else if (event.GetType() == ServiceEvent::UNREGISTERING) + { + if (event.GetServiceReference() == m_ref) + { + // Unget service object and null references. + m_context->UngetService(m_ref); + m_ref = 0; + m_dictionary = NULL; + + // Query to see if we can get another service. + std::vector > refs; + try + { + refs = m_context->GetServiceReferences("(Language=*)"); + } + catch (const std::invalid_argument& e) + { + std::cout << e.what() << std::endl; + } + + if (!refs.empty()) + { + // Get a reference to the first service object. + m_ref = refs.front(); + m_dictionary = m_context->GetService(m_ref); + } + } + } + } + +private: + + // Module context + ModuleContext* m_context; + + // The service reference being used + ServiceReference m_ref; + + // The service object being used + IDictionaryService* m_dictionary; +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient2, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/dictionaryclient2/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryclient2/CMakeLists.txt new file mode 100644 index 0000000000..7e7524a088 --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient2/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client 2" + LIBRARY_NAME "dictionaryclient2") + +set(dictionaryclient2_DEPENDS dictionaryservice) +CreateExample(dictionaryclient2 ${_srcs}) diff --git a/Core/CppMicroServices/examples/dictionaryclient3/Activator.cpp b/Core/CppMicroServices/examples/dictionaryclient3/Activator.cpp new file mode 100644 index 0000000000..a97524435b --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient3/Activator.cpp @@ -0,0 +1,142 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module activator that uses a dictionary + * service to check for the proper spelling of a word by + * checking for its existence in the dictionary. This module + * uses a service tracker to dynamically monitor the availability + * of a dictionary service, instead of providing a custom service + * listener as in Example 4. The module uses the service returned + * by the service tracker, which is selected based on a ranking + * algorithm defined by the C++ Micro Services library. + * Again, the calling thread of the Load() method is used to read + * words from standard input, checking its existence in the dictionary. + * You can stop checking words by entering an empty line, but + * to start checking words again you must unload and then load + * the module again. + */ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_tracker(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Creates a service + * tracker to monitor dictionary services and starts its "word + * checking loop". It will not be able to check any words until + * the service tracker finds a dictionary service; any discovered + * dictionary service will be automatically used by the client. + * It reads words from standard input and checks for their + * existence in the discovered dictionary. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + // Create a service tracker to monitor dictionary services. + m_tracker = new ServiceTracker( + m_context, LDAPFilter(std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=" + + us_service_interface_iid() + ")" + + "(Language=*))") + ); + m_tracker->Open(); + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a word. + std::cout << "Enter word: "; + + std::string word; + std::getline(std::cin, word); + + // Get the selected dictionary, if available. + IDictionaryService* dictionary = m_tracker->GetService(); + + // If the user entered a blank line, then + // exit the loop. + if (word.empty()) + { + break; + } + // If there is no dictionary, then say so. + else if (dictionary == NULL) + { + std::cout << "No dictionary available." << std::endl; + } + // Otherwise print whether the word is correct or not. + else if (dictionary->CheckWord(word)) + { + std::cout << "Correct." << std::endl; + } + else + { + std::cout << "Incorrect." << std::endl; + } + } + + // This automatically closes the tracker + delete m_tracker; + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + } + +private: + + // Module context + ModuleContext* m_context; + + // The service tracker + ServiceTracker* m_tracker; +}; + +US_EXPORT_MODULE_ACTIVATOR(dictionaryclient3, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/dictionaryclient3/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryclient3/CMakeLists.txt new file mode 100644 index 0000000000..44984fbd6e --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryclient3/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Client 3" + LIBRARY_NAME "dictionaryclient3") + +set(dictionaryclient3_DEPENDS dictionaryservice) +CreateExample(dictionaryclient3 ${_srcs}) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/CppMicroServices/examples/dictionaryservice/Activator.cpp similarity index 63% copy from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp copy to Core/CppMicroServices/examples/dictionaryservice/Activator.cpp index bd714f6d54..a7289f7a42 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp +++ b/Core/CppMicroServices/examples/dictionaryservice/Activator.cpp @@ -1,121 +1,116 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ //! [Activator] -#include "DictionaryService.h" +#include "IDictionaryService.h" #include #include -#include #include -// Replace that include with your own base class declaration -#include US_BASECLASS_HEADER - #include -#include #include US_USE_NAMESPACE /** * This class implements a module activator that uses the module * context to register an English language dictionary service * with the C++ Micro Services registry during static initialization * of the module. The dictionary service interface is * defined in a separate file and is implemented by a nested class. */ -class US_ABI_LOCAL MyActivator : public ModuleActivator +class US_ABI_LOCAL Activator : public ModuleActivator { private: /** * A private inner class that implements a dictionary service; - * see DictionaryService for details of the service. + * see IDictionaryService for details of the service. */ - class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService + class DictionaryImpl : public IDictionaryService { // The set of words contained in the dictionary. std::set m_dictionary; public: DictionaryImpl() { m_dictionary.insert("welcome"); m_dictionary.insert("to"); m_dictionary.insert("the"); m_dictionary.insert("micro"); m_dictionary.insert("services"); m_dictionary.insert("tutorial"); } /** - * Implements DictionaryService.checkWord(). Determines + * Implements IDictionaryService::CheckWord(). Determines * if the passed in word is contained in the dictionary. * @param word the word to be checked. * @return true if the word is in the dictionary, * false otherwise. **/ - bool checkWord(const std::string& word) + bool CheckWord(const std::string& word) { std::string lword(word); std::transform(lword.begin(), lword.end(), lword.begin(), ::tolower); return m_dictionary.find(lword) != m_dictionary.end(); } }; std::auto_ptr m_dictionaryService; public: /** * Implements ModuleActivator::Load(). Registers an * instance of a dictionary service using the module context; * attaches properties to the service that can be queried * when performing a service look-up. * @param context the context for the module. */ void Load(ModuleContext* context) { m_dictionaryService.reset(new DictionaryImpl); ServiceProperties props; props["Language"] = std::string("English"); - context->RegisterService(m_dictionaryService.get(), props); + context->RegisterService(m_dictionaryService.get(), props); } /** * Implements ModuleActivator::Unload(). Does nothing since * the C++ Micro Services library will automatically unregister any registered services. * @param context the context for the module. */ void Unload(ModuleContext* /*context*/) { // NOTE: The service is automatically unregistered } }; -US_EXPORT_MODULE_ACTIVATOR(DictionaryServiceModule, MyActivator) +US_EXPORT_MODULE_ACTIVATOR(dictionaryservice, Activator) //![Activator] - -#include - -US_INITIALIZE_MODULE("DictionaryServiceModule", "", "", "1.0.0") - -int main(int /*argc*/, char* /*argv*/[]) -{ - //![GetDictionaryService] - ServiceReference dictionaryServiceRef = GetModuleContext()->GetServiceReference(); - if (dictionaryServiceRef) - { - DictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); - if (dictionaryService) - { - std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->checkWord("Tutorial") << std::endl; - } - } - //![GetDictionaryService] - return 0; -} diff --git a/Core/CppMicroServices/examples/dictionaryservice/CMakeLists.txt b/Core/CppMicroServices/examples/dictionaryservice/CMakeLists.txt new file mode 100644 index 0000000000..ae21e3b14c --- /dev/null +++ b/Core/CppMicroServices/examples/dictionaryservice/CMakeLists.txt @@ -0,0 +1,26 @@ +# The library name for the module +set(_lib_name dictionaryservice) + +# A list of source code files +set(_srcs + Activator.cpp + IDictionaryService.cpp +) + +# Generate module initialization code +usFunctionGenerateModuleInit(_srcs + NAME "Dictionary Service" + LIBRARY_NAME ${_lib_name}) + +# Create the library +add_library(Example-${_lib_name} SHARED ${_srcs}) + +# Link the CppMicroServices library +target_link_libraries(Example-${_lib_name} ${CppMicroServices_LIBRARIES}) + +set_target_properties(Example-${_lib_name} PROPERTIES + LABELS Examples + OUTPUT_NAME ${_lib_name} +) + +#CreateExample(dictionaryservice ${_srcs}) diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.cpp similarity index 90% copy from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp copy to Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.cpp index 9b0abf1b25..ef0ba43dcb 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.cpp @@ -1,31 +1,25 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#include - -US_BEGIN_NAMESPACE - -struct TestModuleAL_Dummy -{ -}; - -US_END_NAMESPACE +#include "IDictionaryService.h" +IDictionaryService::~IDictionaryService() +{} diff --git a/Core/Code/CppMicroServices/test/usServiceControlInterface.h b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.h similarity index 50% copy from Core/Code/CppMicroServices/test/usServiceControlInterface.h copy to Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.h index 129832ff12..df806d843f 100644 --- a/Core/Code/CppMicroServices/test/usServiceControlInterface.h +++ b/Core/CppMicroServices/examples/dictionaryservice/IDictionaryService.h @@ -1,45 +1,58 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ +#ifndef IDICTIONARYSERVICE_H +#define IDICTIONARYSERVICE_H -#ifndef USSERVICECONTROLINTERFACE_H -#define USSERVICECONTROLINTERFACE_H - -#include +//! [service] #include #include -US_BEGIN_NAMESPACE - -struct ServiceControlInterface +#ifdef Example_dictionaryservice_EXPORTS + #define DICTIONAYSERVICE_EXPORT US_ABI_EXPORT +#else + #define DICTIONAYSERVICE_EXPORT US_ABI_IMPORT +#endif + +/** + * A simple service interface that defines a dictionary service. + * A dictionary service simply verifies the existence of a word. + **/ +struct DICTIONAYSERVICE_EXPORT IDictionaryService { - - virtual ~ServiceControlInterface() {} - - virtual void ServiceControl(int service, const std::string& operation, int ranking) = 0; + // Out-of-line virtual desctructor for proper dynamic cast + // support with older versions of gcc. + virtual ~IDictionaryService(); + + /** + * Check for the existence of a word. + * @param word the word to be checked. + * @return true if the word is in the dictionary, + * false otherwise. + **/ + virtual bool CheckWord(const std::string& word) = 0; }; -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(ServiceControlInterface), "org.us.testing.ServiceControlInterface") +US_DECLARE_SERVICE_INTERFACE(IDictionaryService, "IDictionaryService/1.0") +//! [service] -#endif // USSERVICECONTROLINTERFACE_H +#endif // DICTIONARYSERVICE_H diff --git a/Core/CppMicroServices/examples/driver/CMakeLists.txt b/Core/CppMicroServices/examples/driver/CMakeLists.txt new file mode 100644 index 0000000000..f37d796a46 --- /dev/null +++ b/Core/CppMicroServices/examples/driver/CMakeLists.txt @@ -0,0 +1,16 @@ + +if(WIN32) + string(REPLACE "/" "\\\\" CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + string(REPLACE "/" "\\\\" CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +else() + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/usCppMicroServicesExampleDriverConfig.h.in + ${CMAKE_CURRENT_BINARY_DIR}/usCppMicroServicesExampleDriverConfig.h) + +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + +add_executable(CppMicroServicesExampleDriver main.cpp) +target_link_libraries(CppMicroServicesExampleDriver ${CppMicroServices_LIBRARIES}) diff --git a/Core/CppMicroServices/examples/driver/main.cpp b/Core/CppMicroServices/examples/driver/main.cpp new file mode 100644 index 0000000000..f4dcfa7649 --- /dev/null +++ b/Core/CppMicroServices/examples/driver/main.cpp @@ -0,0 +1,300 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include + +#include "usCppMicroServicesExampleDriverConfig.h" + +#if defined(US_PLATFORM_POSIX) + #include +#elif defined(US_PLATFORM_WINDOWS) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include +#else + #error Unsupported platform +#endif + +#include +#include +#include +#include +#include +#include +#include + +US_USE_NAMESPACE + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +std::map GetExampleModules() +{ + std::map names; + names.insert(std::make_pair("Event Listener", "eventlistener")); + names.insert(std::make_pair("Dictionary Service", "dictionaryservice")); + names.insert(std::make_pair("French Dictionary", "frenchdictionary")); + names.insert(std::make_pair("Dictionary Client", "dictionaryclient")); + names.insert(std::make_pair("Dictionary Client 2", "dictionaryclient2")); + names.insert(std::make_pair("Dictionary Client 3", "dictionaryclient3")); + names.insert(std::make_pair("Spell Check Service", "spellcheckservice")); + names.insert(std::make_pair("Spell Check Client", "spellcheckclient")); + return names; +} + +int main(int /*argc*/, char** /*argv*/) +{ + char cmd[256]; + + std::map availableModules = GetExampleModules(); + + /* module path -> lib handle */ + std::map libraryHandles; + + SharedLibrary sharedLib(LIB_PATH, ""); + + std::cout << "> "; + while(std::cin.getline(cmd, sizeof(cmd))) + { + std::string strCmd(cmd); + if (strCmd == "q") + { + break; + } + else if (strCmd == "h") + { + std::cout << std::left << std::setw(15) << "h" << " This help text\n" + << std::setw(15) << "l " << " Load the module with id or name \n" + << std::setw(15) << "u " << " Unload the module with id \n" + << std::setw(15) << "s" << " Print status information\n" + << std::setw(15) << "q" << " Quit\n" << std::flush; + } + else if (strCmd.find("l ") != std::string::npos) + { + std::string idOrName; + idOrName.assign(strCmd.begin()+2, strCmd.end()); + std::stringstream ss(idOrName); + + long int id = -1; + ss >> id; + if (id > 0) + { + Module* module = ModuleRegistry::GetModule(id); + if (!module) + { + std::cout << "Error: unknown id" << std::endl; + } + else if (module->IsLoaded()) + { + std::cout << "Info: module already loaded" << std::endl; + } + else + { + try + { + std::map::iterator libIter = + libraryHandles.find(module->GetLocation()); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + // The module has been loaded previously due to a + // linker dependency + SharedLibrary libHandle(module->GetLocation()); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + } + else + { + Module* module = ModuleRegistry::GetModule(idOrName); + if (!module) + { + try + { + std::map::iterator libIter = + libraryHandles.find(sharedLib.GetFilePath(idOrName)); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + bool libFound = false; + for (std::map::const_iterator availableModuleIter = availableModules.begin(); + availableModuleIter != availableModules.end(); ++availableModuleIter) + { + if (availableModuleIter->second == idOrName) + { + libFound = true; + } + } + if (!libFound) + { + std::cout << "Error: unknown example module" << std::endl; + } + else + { + SharedLibrary libHandle(LIB_PATH, idOrName); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + + std::vector modules; + ModuleRegistry::GetModules(modules); + for (std::vector::const_iterator moduleIter = modules.begin(); + moduleIter != modules.end(); ++moduleIter) + { + availableModules.erase((*moduleIter)->GetName()); + } + + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + else if (!module->IsLoaded()) + { + try + { + const std::string modulePath = module->GetLocation(); + std::map::iterator libIter = + libraryHandles.find(modulePath); + if (libIter != libraryHandles.end()) + { + libIter->second.Load(); + } + else + { + SharedLibrary libHandle(LIB_PATH, idOrName); + libHandle.Load(); + libraryHandles.insert(std::make_pair(libHandle.GetFilePath(), libHandle)); + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + else if (module) + { + std::cout << "Info: module already loaded" << std::endl; + } + } + } + else if (strCmd.find("u ") != std::string::npos) + { + std::stringstream ss(strCmd); + ss.ignore(2); + + long int id = -1; + ss >> id; + + if (id == 1) + { + std::cout << "Info: Unloading not possible" << std::endl; + } + else + { + Module* const module = ModuleRegistry::GetModule(id); + if (module) + { + std::map::iterator libIter = + libraryHandles.find(module->GetLocation()); + if (libIter == libraryHandles.end()) + { + std::cout << "Info: Unloading not possible. The module was loaded by a dependent module." << std::endl; + } + else + { + try + { + libIter->second.Unload(); + + // Check if it has really been unloaded + if (module->IsLoaded()) + { + std::cout << "Info: The module is still referenced by another loaded module. It will be unloaded when all dependent modules are unloaded." << std::endl; + } + } + catch (const std::exception& e) + { + std::cout << e.what() << std::endl; + } + } + } + else + { + std::cout << "Error: unknown id" << std::endl; + } + } + } + else if (strCmd == "s") + { + std::vector modules; + ModuleRegistry::GetModules(modules); + + std::cout << std::left; + + std::cout << "Id | " << std::setw(20) << "Name" << " | " << std::setw(9) << "Status" << std::endl; + std::cout << "-----------------------------------\n"; + + for (std::map::const_iterator nameIter = availableModules.begin(); + nameIter != availableModules.end(); ++nameIter) + { + std::cout << " - | " << std::setw(20) << nameIter->second << " | " << std::setw(9) << "-" << std::endl; + } + + for (std::vector::const_iterator moduleIter = modules.begin(); + moduleIter != modules.end(); ++moduleIter) + { + std::cout << std::right << std::setw(2) << (*moduleIter)->GetModuleId() << std::left << " | "; + std::cout << std::setw(20) << (*moduleIter)->GetName() << " | "; + std::cout << std::setw(9) << ((*moduleIter)->IsLoaded() ? "LOADED" : "UNLOADED"); + std::cout << std::endl; + } + } + else + { + std::cout << "Unknown command: " << strCmd << " (type 'h' for help)" << std::endl; + } + std::cout << "> "; + } + + return 0; +} diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h b/Core/CppMicroServices/examples/driver/usCppMicroServicesExampleDriverConfig.h.in similarity index 59% copy from Core/Code/CppMicroServices/src/util/usUncompressResourceData.h copy to Core/CppMicroServices/examples/driver/usCppMicroServicesExampleDriverConfig.h.in index a3e82f3679..880a0cfa25 100644 --- a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h +++ b/Core/CppMicroServices/examples/driver/usCppMicroServicesExampleDriverConfig.h.in @@ -1,33 +1,41 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#ifndef USUNCOMPRESSRESOURCEDATA_H -#define USUNCOMPRESSRESOURCEDATA_H +#ifndef USEXAMPLEDRIVERCONFIG_H +#define USEXAMPLEDRIVERCONFIG_H #include "usConfig.h" -US_BEGIN_NAMESPACE - -US_EXPORT unsigned char* UncompressResourceData(const unsigned char* data, std::size_t size, std::size_t* uncompressedSize); - -US_END_NAMESPACE - -#endif // USUNCOMPRESSRESOURCEDATA_H +#ifdef US_PLATFORM_POSIX +#define PATH_SEPARATOR "/" +#else +#define PATH_SEPARATOR "\\" +#endif + +#ifdef CMAKE_INTDIR +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE@" PATH_SEPARATOR CMAKE_INTDIR +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE@" PATH_SEPARATOR CMAKE_INTDIR +#else +#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY_NATIVE@" +#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY_NATIVE@" +#endif + +#endif // USEXAMPLEDRIVERCONFIG_H diff --git a/Core/CppMicroServices/examples/eventlistener/Activator.cpp b/Core/CppMicroServices/examples/eventlistener/Activator.cpp new file mode 100644 index 0000000000..d7b9ae245f --- /dev/null +++ b/Core/CppMicroServices/examples/eventlistener/Activator.cpp @@ -0,0 +1,90 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a simple module that utilizes the CppMicroServices's + * event mechanism to listen for service events. Upon receiving a service event, + * it prints out the event's details. + */ +class Activator : public ModuleActivator +{ + +private: + + /** + * Implements ModuleActivator::Load(). Prints a message and adds a member + * function to the module context as a service listener. + * + * @param context the framework context for the module. + */ + void Load(ModuleContext* context) + { + std::cout << "Starting to listen for service events." << std::endl; + context->AddServiceListener(this, &Activator::ServiceChanged); + } + + /** + * Implements ModuleActivator::Unload(). Prints a message and removes the + * member function from the module context as a service listener. + * + * @param context the framework context for the module. + */ + void Unload(ModuleContext* context) + { + context->RemoveServiceListener(this, &Activator::ServiceChanged); + std::cout << "Stopped listening for service events." << std::endl; + + // Note: It is not required that we remove the listener here, + // since the framework will do it automatically anyway. + } + + /** + * Prints the details of any service event from the framework. + * + * @param event the fired service event. + */ + void ServiceChanged(const ServiceEvent event) + { + std::string objectClass = ref_any_cast >(event.GetServiceReference().GetProperty(ServiceConstants::OBJECTCLASS())).front(); + + if (event.GetType() == ServiceEvent::REGISTERED) + { + std::cout << "Ex1: Service of type " << objectClass << " registered." << std::endl; + } + else if (event.GetType() == ServiceEvent::UNREGISTERING) + { + std::cout << "Ex1: Service of type " << objectClass << " unregistered." << std::endl; + } + else if (event.GetType() == ServiceEvent::MODIFIED) + { + std::cout << "Ex1: Service of type " << objectClass << " modified." << std::endl; + } + } +}; + +US_EXPORT_MODULE_ACTIVATOR(eventlistener, Activator) +//! [Activator] diff --git a/Core/CppMicroServices/examples/eventlistener/CMakeLists.txt b/Core/CppMicroServices/examples/eventlistener/CMakeLists.txt new file mode 100644 index 0000000000..2c6dce49be --- /dev/null +++ b/Core/CppMicroServices/examples/eventlistener/CMakeLists.txt @@ -0,0 +1,7 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Event Listener" + LIBRARY_NAME "eventlistener") + +CreateExample(eventlistener ${_srcs}) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/CppMicroServices/examples/frenchdictionary/Activator.cpp similarity index 56% copy from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp copy to Core/CppMicroServices/examples/frenchdictionary/Activator.cpp index bd714f6d54..cb70512826 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp +++ b/Core/CppMicroServices/examples/frenchdictionary/Activator.cpp @@ -1,121 +1,119 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ //! [Activator] -#include "DictionaryService.h" +#include "IDictionaryService.h" #include #include #include #include -// Replace that include with your own base class declaration -#include US_BASECLASS_HEADER - #include #include #include US_USE_NAMESPACE /** * This class implements a module activator that uses the module - * context to register an English language dictionary service + * context to register a French language dictionary service * with the C++ Micro Services registry during static initialization * of the module. The dictionary service interface is - * defined in a separate file and is implemented by a nested class. + * defined in Example 2 (dictionaryservice) and is implemented by a + * nested class. This class is identical to the class in Example 2, + * except that the dictionary contains French words. */ -class US_ABI_LOCAL MyActivator : public ModuleActivator +class US_ABI_LOCAL Activator : public ModuleActivator { private: /** * A private inner class that implements a dictionary service; * see DictionaryService for details of the service. */ - class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService + class DictionaryImpl : public IDictionaryService { // The set of words contained in the dictionary. std::set m_dictionary; public: DictionaryImpl() { - m_dictionary.insert("welcome"); - m_dictionary.insert("to"); - m_dictionary.insert("the"); + m_dictionary.insert("bienvenue"); + m_dictionary.insert("au"); + m_dictionary.insert("tutoriel"); m_dictionary.insert("micro"); m_dictionary.insert("services"); - m_dictionary.insert("tutorial"); } /** * Implements DictionaryService.checkWord(). Determines * if the passed in word is contained in the dictionary. * @param word the word to be checked. * @return true if the word is in the dictionary, * false otherwise. **/ - bool checkWord(const std::string& word) + bool CheckWord(const std::string& word) { std::string lword(word); std::transform(lword.begin(), lword.end(), lword.begin(), ::tolower); return m_dictionary.find(lword) != m_dictionary.end(); } }; std::auto_ptr m_dictionaryService; public: /** * Implements ModuleActivator::Load(). Registers an * instance of a dictionary service using the module context; * attaches properties to the service that can be queried * when performing a service look-up. * @param context the context for the module. */ void Load(ModuleContext* context) { m_dictionaryService.reset(new DictionaryImpl); ServiceProperties props; - props["Language"] = std::string("English"); - context->RegisterService(m_dictionaryService.get(), props); + props["Language"] = std::string("French"); + context->RegisterService(m_dictionaryService.get(), props); } /** * Implements ModuleActivator::Unload(). Does nothing since * the C++ Micro Services library will automatically unregister any registered services. * @param context the context for the module. */ void Unload(ModuleContext* /*context*/) { // NOTE: The service is automatically unregistered } }; -US_EXPORT_MODULE_ACTIVATOR(DictionaryServiceModule, MyActivator) +US_EXPORT_MODULE_ACTIVATOR(frenchdictionary, Activator) //![Activator] - -#include - -US_INITIALIZE_MODULE("DictionaryServiceModule", "", "", "1.0.0") - -int main(int /*argc*/, char* /*argv*/[]) -{ - //![GetDictionaryService] - ServiceReference dictionaryServiceRef = GetModuleContext()->GetServiceReference(); - if (dictionaryServiceRef) - { - DictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); - if (dictionaryService) - { - std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->checkWord("Tutorial") << std::endl; - } - } - //![GetDictionaryService] - return 0; -} diff --git a/Core/CppMicroServices/examples/frenchdictionary/CMakeLists.txt b/Core/CppMicroServices/examples/frenchdictionary/CMakeLists.txt new file mode 100644 index 0000000000..d5c0a649dd --- /dev/null +++ b/Core/CppMicroServices/examples/frenchdictionary/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "French Dictionary" + LIBRARY_NAME "frenchdictionary") + +set(frenchdictionary_DEPENDS dictionaryservice) +CreateExample(frenchdictionary ${_srcs}) diff --git a/Core/CppMicroServices/examples/makefile/IDictionaryService.cpp b/Core/CppMicroServices/examples/makefile/IDictionaryService.cpp new file mode 100644 index 0000000000..47e5097506 --- /dev/null +++ b/Core/CppMicroServices/examples/makefile/IDictionaryService.cpp @@ -0,0 +1,5 @@ +#include "IDictionaryService.h" + +IDictionaryService::~IDictionaryService() +{ +} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h b/Core/CppMicroServices/examples/makefile/IDictionaryService.h similarity index 52% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h rename to Core/CppMicroServices/examples/makefile/IDictionaryService.h index 304d76c6c3..1f003f955d 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h +++ b/Core/CppMicroServices/examples/makefile/IDictionaryService.h @@ -1,27 +1,33 @@ -#ifndef DICTIONARYSERVICE_H -#define DICTIONARYSERVICE_H +#ifndef IDICTIONARYSERVICE_H +#define IDICTIONARYSERVICE_H #include #include +#ifdef MODULE_EXPORTS + #define MODULE_EXPORT US_ABI_EXPORT +#else + #define MODULE_EXPORT US_ABI_IMPORT +#endif + /** * A simple service interface that defines a dictionary service. * A dictionary service simply verifies the existence of a word. **/ -struct DictionaryService +struct MODULE_EXPORT IDictionaryService { - virtual ~DictionaryService() {} + virtual ~IDictionaryService(); /** * Check for the existence of a word. * @param word the word to be checked. * @return true if the word is in the dictionary, * false otherwise. **/ - virtual bool checkWord(const std::string& word) = 0; + virtual bool CheckWord(const std::string& word) = 0; }; -US_DECLARE_SERVICE_INTERFACE(DictionaryService, "DictionaryService/1.0") +US_DECLARE_SERVICE_INTERFACE(IDictionaryService, "IDictionaryService/1.0") #endif // DICTIONARYSERVICE_H diff --git a/Core/CppMicroServices/examples/makefile/Makefile b/Core/CppMicroServices/examples/makefile/Makefile new file mode 100644 index 0000000000..0e4d21a6d2 --- /dev/null +++ b/Core/CppMicroServices/examples/makefile/Makefile @@ -0,0 +1,26 @@ +CXX = g++ +CXXFLAGS = -g -Wall -Wno-unused -pedantic -fPIC $(CppMicroServices_CXX_FLAGS) +LDFLAGS = -Wl,-rpath=$(CppMicroServices_ROOT)/lib -Wl,-rpath=. +LDLIBS = -lCppMicroServices + +INCLUDEDIRS = -I$(CppMicroServices_ROOT)/include/CppMicroServices +LIBDIRS = -L$(CppMicroServices_ROOT)/lib/CppMicroServices -L. + +all : main libmodule.so + +main: libmodule.so main.o + $(CXX) -o $@ $^ $(CXXFLAGS) $(LDFLAGS) $(INCLUDEDIRS) $(LIBDIRS) $(LDLIBS) -lmodule + +libmodule.so: module.o IDictionaryService.o + $(CXX) -shared -o $@ $^ $(CXXFLAGS) $(LDFLAGS) $(INCLUDEDIRS) $(LIBDIRS) $(LDLIBS) + +main.o: main.cpp + $(CXX) $(CXXFLAGS) $(INCLUDEDIRS) -c $< -o $@ + +%.o: %.cpp + $(CXX) $(CXXFLAGS) -DMODULE_EXPORTS $(INCLUDEDIRS) -c $< -o $@ + +.PHONY : clean + +clean: + rm -f *.o diff --git a/Core/CppMicroServices/examples/makefile/main.cpp b/Core/CppMicroServices/examples/makefile/main.cpp new file mode 100644 index 0000000000..fe66aa18b3 --- /dev/null +++ b/Core/CppMicroServices/examples/makefile/main.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +#include "IDictionaryService.h" + +US_USE_NAMESPACE + +int main(int /*argc*/, char* /*argv*/[]) +{ + ServiceReference dictionaryServiceRef = + GetModuleContext()->GetServiceReference(); + if (dictionaryServiceRef) + { + IDictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); + if (dictionaryService) + { + std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->CheckWord("Tutorial") << std::endl; + } + } +} + +#include + +US_INITIALIZE_EXECUTABLE("main") diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/CppMicroServices/examples/makefile/module.cpp similarity index 56% rename from Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp rename to Core/CppMicroServices/examples/makefile/module.cpp index bd714f6d54..e5260d7720 100644 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp +++ b/Core/CppMicroServices/examples/makefile/module.cpp @@ -1,121 +1,102 @@ - -//! [Activator] -#include "DictionaryService.h" - #include #include #include #include -// Replace that include with your own base class declaration -#include US_BASECLASS_HEADER +#include "IDictionaryService.h" #include #include #include US_USE_NAMESPACE /** * This class implements a module activator that uses the module * context to register an English language dictionary service * with the C++ Micro Services registry during static initialization * of the module. The dictionary service interface is * defined in a separate file and is implemented by a nested class. */ class US_ABI_LOCAL MyActivator : public ModuleActivator { private: /** * A private inner class that implements a dictionary service; * see DictionaryService for details of the service. */ - class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService + class DictionaryImpl : public IDictionaryService { // The set of words contained in the dictionary. - std::set m_dictionary; + std::set m_Dictionary; public: DictionaryImpl() { - m_dictionary.insert("welcome"); - m_dictionary.insert("to"); - m_dictionary.insert("the"); - m_dictionary.insert("micro"); - m_dictionary.insert("services"); - m_dictionary.insert("tutorial"); + m_Dictionary.insert("welcome"); + m_Dictionary.insert("to"); + m_Dictionary.insert("the"); + m_Dictionary.insert("micro"); + m_Dictionary.insert("services"); + m_Dictionary.insert("tutorial"); } /** - * Implements DictionaryService.checkWord(). Determines + * Implements IDictionaryService::CheckWord(). Determines * if the passed in word is contained in the dictionary. + * * @param word the word to be checked. * @return true if the word is in the dictionary, * false otherwise. **/ - bool checkWord(const std::string& word) + bool CheckWord(const std::string& word) { std::string lword(word); std::transform(lword.begin(), lword.end(), lword.begin(), ::tolower); - return m_dictionary.find(lword) != m_dictionary.end(); + return m_Dictionary.find(lword) != m_Dictionary.end(); } }; - std::auto_ptr m_dictionaryService; + std::auto_ptr m_DictionaryService; public: /** * Implements ModuleActivator::Load(). Registers an * instance of a dictionary service using the module context; * attaches properties to the service that can be queried * when performing a service look-up. + * * @param context the context for the module. */ void Load(ModuleContext* context) { - m_dictionaryService.reset(new DictionaryImpl); + m_DictionaryService.reset(new DictionaryImpl); ServiceProperties props; props["Language"] = std::string("English"); - context->RegisterService(m_dictionaryService.get(), props); + context->RegisterService(m_DictionaryService.get(), props); } /** * Implements ModuleActivator::Unload(). Does nothing since * the C++ Micro Services library will automatically unregister any registered services. + * * @param context the context for the module. */ void Unload(ModuleContext* /*context*/) { // NOTE: The service is automatically unregistered } }; -US_EXPORT_MODULE_ACTIVATOR(DictionaryServiceModule, MyActivator) -//![Activator] +US_EXPORT_MODULE_ACTIVATOR(module, MyActivator) #include -US_INITIALIZE_MODULE("DictionaryServiceModule", "", "", "1.0.0") - -int main(int /*argc*/, char* /*argv*/[]) -{ - //![GetDictionaryService] - ServiceReference dictionaryServiceRef = GetModuleContext()->GetServiceReference(); - if (dictionaryServiceRef) - { - DictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); - if (dictionaryService) - { - std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->checkWord("Tutorial") << std::endl; - } - } - //![GetDictionaryService] - return 0; -} +US_INITIALIZE_MODULE("My Module", "module") diff --git a/Core/CppMicroServices/examples/spellcheckclient/Activator.cpp b/Core/CppMicroServices/examples/spellcheckclient/Activator.cpp new file mode 100644 index 0000000000..7014fe46fa --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckclient/Activator.cpp @@ -0,0 +1,143 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "ISpellCheckService.h" + +#include +#include +#include + +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module that uses a spell checker + * service to check the spelling of a passage. This module + * is essentially identical to Example 5, in that it uses the + * Service Tracker to monitor the dynamic availability of the + * spell checker service. When loading this module, the thread + * calling the Load() method is used to read passages from + * standard input. You can stop spell checking passages by + * entering an empty line, but to start spell checking again + * you must un-load and then load the module again. +**/ +class US_ABI_LOCAL Activator : public ModuleActivator +{ + +public: + + Activator() + : m_context(NULL) + , m_tracker(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Creates a service + * tracker object to monitor spell checker services. Enters + * a spell check loop where it reads passages from standard + * input and checks their spelling using the spell checker service. + * + * \note It is very bad practice to use the calling thread to perform a + * lengthy process like this; this is only done for the purpose of + * the tutorial. + * + * @param context the module context for this module. + */ + void Load(ModuleContext *context) + { + m_context = context; + + // Create a service tracker to monitor spell check services. + m_tracker = new ServiceTracker(m_context); + m_tracker->Open(); + + std::cout << "Enter a blank line to exit." << std::endl; + + // Loop endlessly until the user enters a blank line + while (std::cin) + { + // Ask the user to enter a passage. + std::cout << "Enter passage: "; + + std::string passage; + std::getline(std::cin, passage); + + // Get the selected spell check service, if available. + ISpellCheckService* checker = m_tracker->GetService(); + + // If the user entered a blank line, then + // exit the loop. + if (passage.empty()) + { + break; + } + // If there is no spell checker, then say so. + else if (checker == NULL) + { + std::cout << "No spell checker available." << std::endl; + } + // Otherwise check passage and print misspelled words. + else + { + std::vector errors = checker->Check(passage); + + if (errors.empty()) + { + std::cout << "Passage is correct." << std::endl; + } + else + { + std::cout << "Incorrect word(s):" << std::endl; + for (std::size_t i = 0; i < errors.size(); ++i) + { + std::cout << " " << errors[i] << std::endl; + } + } + } + } + + // This automatically closes the tracker + delete m_tracker; + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unget any used services. + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + } + +private: + + // Module context + ModuleContext* m_context; + + // The service tracker + ServiceTracker* m_tracker; +}; + +US_EXPORT_MODULE_ACTIVATOR(spellcheckclient, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/spellcheckclient/CMakeLists.txt b/Core/CppMicroServices/examples/spellcheckclient/CMakeLists.txt new file mode 100644 index 0000000000..7e28ef4b12 --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckclient/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Spell Check Client" + LIBRARY_NAME "spellcheckclient") + +set(spellcheckclient_DEPENDS spellcheckservice) +CreateExample(spellcheckclient ${_srcs}) diff --git a/Core/CppMicroServices/examples/spellcheckservice/Activator.cpp b/Core/CppMicroServices/examples/spellcheckservice/Activator.cpp new file mode 100644 index 0000000000..9ad3d882e4 --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckservice/Activator.cpp @@ -0,0 +1,225 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +//! [Activator] +#include "IDictionaryService.h" +#include "ISpellCheckService.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +US_USE_NAMESPACE + +/** + * This class implements a module that implements a spell + * checker service. The spell checker service uses all available + * dictionary services to check for the existence of words in + * a given sentence. This module uses a ServiceTracker to + * monitors the dynamic availability of dictionary services, + * and to aggregate all available dictionary services as they + * arrive and depart. The spell checker service is only registered + * if there are dictionary services available, thus the spell + * checker service will appear and disappear as dictionary + * services appear and disappear, respectively. +**/ +class US_ABI_LOCAL Activator : public ModuleActivator, public ServiceTrackerCustomizer +{ + +private: + + /** + * A private inner class that implements a spell check service; see + * ISpellCheckService for details of the service. + */ + class SpellCheckImpl : public ISpellCheckService + { + + private: + + typedef std::map, IDictionaryService*> RefToServiceType; + RefToServiceType m_refToSvcMap; + + public: + + /** + * Implements ISpellCheckService::Check(). Checks the given passage for + * misspelled words. + * + * @param passage the passage to spell check. + * @return A list of misspelled words. + */ + std::vector Check(const std::string& passage) + { + std::vector errorList; + + // No misspelled words for an empty string. + if (passage.empty()) + { + return errorList; + } + + // Tokenize the passage using spaces and punctuation. + const char* delimiters = " ,.!?;:"; + char* passageCopy = new char[passage.size()+1]; + std::memcpy(passageCopy, passage.c_str(), passage.size()+1); + char* pch = std::strtok(passageCopy, delimiters); + + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + // Loop through each word in the passage. + while (pch) + { + std::string word(pch); + + bool correct = false; + + // Check each available dictionary for the current word. + for (RefToServiceType::const_iterator i = m_refToSvcMap.begin(); + (!correct) && (i != m_refToSvcMap.end()); ++i) + { + IDictionaryService* dictionary = i->second; + + if (dictionary->CheckWord(word)) + { + correct = true; + } + } + + // If the word is not correct, then add it + // to the incorrect word list. + if (!correct) + { + errorList.push_back(word); + } + + pch = std::strtok(NULL, delimiters); + } + } + + delete[] passageCopy; + + return errorList; + } + + int AddDictionary(const ServiceReference& ref, IDictionaryService* dictionary) + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + m_refToSvcMap.insert(std::make_pair(ref, dictionary)); + + return m_refToSvcMap.size(); + } + + int RemoveDictionary(const ServiceReference& ref) + { + // Lock the m_refToSvcMap member using your favorite thread library here... + // MutexLocker lock(&m_refToSvcMapMutex) + + m_refToSvcMap.erase(ref); + + return m_refToSvcMap.size(); + } + }; + + virtual IDictionaryService* AddingService(const ServiceReference& reference) + { + IDictionaryService* dictionary = m_context->GetService(reference); + int count = m_spellCheckService->AddDictionary(reference, dictionary); + if (!m_spellCheckReg && count > 1) + { + m_spellCheckReg = m_context->RegisterService(m_spellCheckService.get()); + } + return dictionary; + } + + virtual void ModifiedService(const ServiceReference& /*reference*/, + IDictionaryService* /*service*/) + { + // do nothing + } + + virtual void RemovedService(const ServiceReference& reference, + IDictionaryService* /*service*/) + { + if (m_spellCheckService->RemoveDictionary(reference) < 2 && m_spellCheckReg) + { + m_spellCheckReg.Unregister(); + m_spellCheckReg = 0; + } + } + + std::auto_ptr m_spellCheckService; + ServiceRegistration m_spellCheckReg; + + ModuleContext* m_context; + std::auto_ptr > m_tracker; + +public: + + Activator() + : m_context(NULL) + {} + + /** + * Implements ModuleActivator::Load(). Registers an + * instance of a dictionary service using the module context; + * attaches properties to the service that can be queried + * when performing a service look-up. + * + * @param context the context for the module. + */ + void Load(ModuleContext* context) + { + m_context = context; + + m_spellCheckService.reset(new SpellCheckImpl); + m_tracker.reset(new ServiceTracker(context, this)); + m_tracker->Open(); + } + + /** + * Implements ModuleActivator::Unload(). Does nothing since + * the C++ Micro Services library will automatically unregister any registered services + * and release any used services. + * + * @param context the context for the module. + */ + void Unload(ModuleContext* /*context*/) + { + // NOTE: The service is automatically unregistered + + m_tracker->Close(); + } + +}; + +US_EXPORT_MODULE_ACTIVATOR(spellcheckservice, Activator) +//![Activator] diff --git a/Core/CppMicroServices/examples/spellcheckservice/CMakeLists.txt b/Core/CppMicroServices/examples/spellcheckservice/CMakeLists.txt new file mode 100644 index 0000000000..a86d8153a6 --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckservice/CMakeLists.txt @@ -0,0 +1,8 @@ +set(_srcs Activator.cpp ISpellCheckService.cpp) + +usFunctionGenerateModuleInit(_srcs + NAME "Spell Check Service" + LIBRARY_NAME "spellcheckservice") + +set(spellcheckservice_DEPENDS dictionaryservice) +CreateExample(spellcheckservice ${_srcs}) diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.cpp similarity index 90% copy from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp copy to Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.cpp index 9b0abf1b25..4a2d238a38 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.cpp @@ -1,31 +1,25 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#include - -US_BEGIN_NAMESPACE - -struct TestModuleAL_Dummy -{ -}; - -US_END_NAMESPACE +#include "ISpellCheckService.h" +ISpellCheckService::~ISpellCheckService() +{} diff --git a/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.h b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.h new file mode 100644 index 0000000000..679235801b --- /dev/null +++ b/Core/CppMicroServices/examples/spellcheckservice/ISpellCheckService.h @@ -0,0 +1,64 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef ISPELLCHECKSERVICE_H +#define ISPELLCHECKSERVICE_H + +//! [service] +#include + +#include +#include + +#ifdef Example_spellcheckservice_EXPORTS + #define SPELLCHECKSERVICE_EXPORT US_ABI_EXPORT +#else + #define SPELLCHECKSERVICE_EXPORT US_ABI_IMPORT +#endif + +/** + * A simple service interface that defines a spell check service. A spell check + * service checks the spelling of all words in a given passage. A passage is any + * number of words separated by a space character and the following punctuation + * marks: comma, period, exclamation mark, question mark, semi-colon, and colon. + */ +struct SPELLCHECKSERVICE_EXPORT ISpellCheckService +{ + // Out-of-line virtual desctructor for proper dynamic cast + // support with older versions of gcc. + virtual ~ISpellCheckService(); + + /** + * Checks a given passage for spelling errors. A passage is any number of + * words separated by a space and any of the following punctuation marks: + * comma (,), period (.), exclamation mark (!), question mark (?), + * semi-colon (;), and colon(:). + * + * @param passage the passage to spell check. + * @return A list of misspelled words. + */ + virtual std::vector Check(const std::string& passage) = 0; +}; + +US_DECLARE_SERVICE_INTERFACE(ISpellCheckService, "ISpellCheckService/1.0") +//! [service] +//! +#endif // ISPELLCHECKSERVICE_H diff --git a/Core/Code/CppMicroServices/src/CMakeLists.txt b/Core/CppMicroServices/src/CMakeLists.txt similarity index 78% rename from Core/Code/CppMicroServices/src/CMakeLists.txt rename to Core/CppMicroServices/src/CMakeLists.txt index 45a9814854..5244cbb638 100644 --- a/Core/Code/CppMicroServices/src/CMakeLists.txt +++ b/Core/CppMicroServices/src/CMakeLists.txt @@ -1,184 +1,190 @@ #----------------------------------------------------------------------------- # US source files #----------------------------------------------------------------------------- set(_srcs util/usAny.cpp + util/jsoncpp.cpp + util/usSharedLibrary.cpp + util/usThreads.cpp util/usUncompressResourceData.c util/usUncompressResourceData.cpp - util/usThreads.cpp util/usUtils.cpp service/usLDAPExpr.cpp service/usLDAPFilter.cpp service/usServiceException.cpp service/usServiceEvent.cpp service/usServiceListenerEntry.cpp service/usServiceListenerEntry_p.h service/usServiceListeners.cpp service/usServiceListeners_p.h + service/usServiceObjects.cpp service/usServiceProperties.cpp - service/usServiceReference.cpp - service/usServiceReferencePrivate.cpp - service/usServiceRegistration.cpp - service/usServiceRegistrationPrivate.cpp + service/usServicePropertiesImpl.cpp + service/usServiceReferenceBase.cpp + service/usServiceReferenceBasePrivate.cpp + service/usServiceRegistrationBase.cpp + service/usServiceRegistrationBasePrivate.cpp service/usServiceRegistry.cpp service/usServiceRegistry_p.h module/usCoreModuleContext_p.h module/usCoreModuleContext.cpp module/usModuleContext.cpp module/usModule.cpp module/usModuleEvent.cpp module/usModuleInfo.cpp + module/usModuleManifest.cpp module/usModulePrivate.cpp module/usModuleRegistry.cpp module/usModuleResource.cpp module/usModuleResourceBuffer.cpp module/usModuleResourceStream.cpp module/usModuleResourceTree.cpp module/usModuleSettings.cpp module/usModuleUtils.cpp module/usModuleVersion.cpp ) set(_private_headers util/usAtomicInt_p.h util/usFunctor_p.h util/usStaticInit_p.h util/usThreads_p.h util/usUtils_p.h util/dirent_win32_p.h util/stdint_p.h util/stdint_vc_p.h + service/usServicePropertiesImpl_p.h service/usServiceTracker.tpp service/usServiceTrackerPrivate.h service/usServiceTrackerPrivate.tpp service/usTrackedService_p.h service/usTrackedServiceListener_p.h service/usTrackedService.tpp module/usModuleAbstractTracked_p.h module/usModuleAbstractTracked.tpp module/usModuleResourceBuffer_p.h module/usModuleResourceTree_p.h module/usModuleUtils_p.h ) set(_public_headers util/usAny.h util/usSharedData.h + util/usSharedLibrary.h util/usUncompressResourceData.h service/usLDAPFilter.h + service/usPrototypeServiceFactory.h service/usServiceEvent.h service/usServiceException.h + service/usServiceFactory.h service/usServiceInterface.h + service/usServiceObjects.h service/usServiceProperties.h service/usServiceReference.h + service/usServiceReferenceBase.h service/usServiceRegistration.h + service/usServiceRegistrationBase.h service/usServiceTracker.h service/usServiceTrackerCustomizer.h module/usGetModuleContext.h module/usModule.h module/usModuleActivator.h module/usModuleContext.h module/usModuleEvent.h module/usModuleImport.h module/usModuleInfo.h module/usModuleInitialization.h module/usModuleRegistry.h module/usModuleResource.h module/usModuleResourceStream.h module/usModuleSettings.h module/usModuleVersion.h ) -if(_us_baseclass_default) - list(APPEND _public_headers util/usBase.h) -endif() - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND _public_headers service/usServiceFactory.h) -endif() - if(US_IS_EMBEDDED) set(US_SOURCES ) get_filename_component(_path_prefix "${PROJECT_SOURCE_DIR}" NAME) set(_path_prefix "${_path_prefix}/src") foreach(_src ${_srcs} ${_public_headers} ${_private_headers}) list(APPEND US_SOURCES ${_path_prefix}/${_src}) endforeach() set(US_SOURCES ${US_SOURCES} PARENT_SCOPE) endif() #----------------------------------------------------------------------------- # Create library (only if not in embedded mode) #----------------------------------------------------------------------------- if(NOT US_IS_EMBEDDED) include_directories(${US_INTERNAL_INCLUDE_DIRS}) - if(US_LINK_DIRS) - link_directories(${US_LINK_DIRS}) - endif() - usFunctionGenerateModuleInit(_srcs NAME ${PROJECT_NAME} VERSION "0.9.0") + usFunctionGenerateModuleInit(_srcs NAME ${PROJECT_NAME}) + usFunctionEmbedResources(_srcs LIBRARY_NAME ${PROJECT_NAME} + ROOT_DIR resources + FILES manifest.json) add_library(${PROJECT_NAME} ${_srcs} ${_public_headers} ${_private_headers} ${us_config_h_file}) - if(NOT US_IS_EMBEDDED AND US_LINK_FLAGS) + if(US_LINK_FLAGS) set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "${US_LINK_FLAGS}") endif() set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS US_FORCE_MODULE_INIT) - set_property(TARGET ${PROJECT_NAME} PROPERTY FRAMEWORK 1) + set_target_properties(${PROJECT_NAME} PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + ) if(US_LINK_LIBRARIES) - target_link_libraries(${PROJECT_NAME} ${_link_libraries}) + target_link_libraries(${PROJECT_NAME} ${US_LINK_LIBRARIES}) endif() endif() #----------------------------------------------------------------------------- # Configure public header wrappers #----------------------------------------------------------------------------- set(US_PUBLIC_HEADERS ${_public_headers}) if(US_HEADER_PREFIX) set(US_PUBLIC_HEADERS ) foreach(_public_header ${_public_headers}) get_filename_component(_public_header_basename ${_public_header} NAME_WE) set(_us_public_header ${_public_header_basename}.h) string(SUBSTRING "${_public_header_basename}" 2 -1 _public_header_basename) set(_header_wrapper "${PROJECT_BINARY_DIR}/include/${US_HEADER_PREFIX}${_public_header_basename}.h") configure_file(${PROJECT_SOURCE_DIR}/CMake/usPublicHeaderWrapper.h.in ${_header_wrapper} @ONLY) list(APPEND US_PUBLIC_HEADERS ${_header_wrapper}) endforeach() endif() foreach(_header ${_public_headers} ${_private_headers}) get_filename_component(_header_name "${_header}" NAME) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${_header} "${PROJECT_BINARY_DIR}/include/${_header_name}") endforeach() if(NOT US_IS_EMBEDDED) set_property(TARGET ${PROJECT_NAME} PROPERTY PUBLIC_HEADER ${US_PUBLIC_HEADERS}) set_property(TARGET ${PROJECT_NAME} PROPERTY PRIVATE_HEADER ${_private_headers} ${us_config_h_file}) else() set(US_PUBLIC_HEADERS ${US_PUBLIC_HEADERS} PARENT_SCOPE) set(US_PRIVATE_HEADERS ${US_PRIVATE_HEADERS} PARENT_SCOPE) endif() #----------------------------------------------------------------------------- # Install support (only if not in embedded mode) #----------------------------------------------------------------------------- if(NOT US_IS_EMBEDDED) - install(TARGETS ${PROJECT_NAME} FRAMEWORK DESTINATION . - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib - PUBLIC_HEADER DESTINATION include - PRIVATE_HEADER DESTINATION include) + install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}Targets + RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR} COMPONENT sdk + LIBRARY DESTINATION ${LIBRARY_INSTALL_DIR} COMPONENT sdk + ARCHIVE DESTINATION ${ARCHIVE_INSTALL_DIR} COMPONENT sdk + PUBLIC_HEADER DESTINATION ${HEADER_INSTALL_DIR} COMPONENT sdk + PRIVATE_HEADER DESTINATION ${HEADER_INSTALL_DIR} COMPONENT sdk) endif() - diff --git a/Core/Code/CppMicroServices/src/module/usCoreModuleContext.cpp b/Core/CppMicroServices/src/module/usCoreModuleContext.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usCoreModuleContext.cpp rename to Core/CppMicroServices/src/module/usCoreModuleContext.cpp diff --git a/Core/Code/CppMicroServices/src/module/usCoreModuleContext_p.h b/Core/CppMicroServices/src/module/usCoreModuleContext_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usCoreModuleContext_p.h rename to Core/CppMicroServices/src/module/usCoreModuleContext_p.h diff --git a/Core/Code/CppMicroServices/src/module/usGetModuleContext.h b/Core/CppMicroServices/src/module/usGetModuleContext.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usGetModuleContext.h rename to Core/CppMicroServices/src/module/usGetModuleContext.h diff --git a/Core/Code/CppMicroServices/src/module/usModule.cpp b/Core/CppMicroServices/src/module/usModule.cpp similarity index 82% rename from Core/Code/CppMicroServices/src/module/usModule.cpp rename to Core/CppMicroServices/src/module/usModule.cpp index dbe528c288..f12b12b6e4 100644 --- a/Core/Code/CppMicroServices/src/module/usModule.cpp +++ b/Core/CppMicroServices/src/module/usModule.cpp @@ -1,281 +1,319 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usModule.h" #include "usModuleContext.h" #include "usModuleActivator.h" #include "usModulePrivate.h" #include "usModuleResource.h" #include "usModuleSettings.h" #include "usCoreModuleContext_p.h" US_BEGIN_NAMESPACE const std::string& Module::PROP_ID() { static const std::string s("module.id"); return s; } const std::string& Module::PROP_NAME() { static const std::string s("module.name"); return s; } const std::string& Module::PROP_LOCATION() { static const std::string s("module.location"); return s; } -const std::string& Module::PROP_MODULE_DEPENDS() +const std::string& Module::PROP_VERSION() { - static const std::string s("module.module_depends"); + static const std::string s("module.version"); return s; } -const std::string& Module::PROP_LIB_DEPENDS() + +const std::string&Module::PROP_VENDOR() { - static const std::string s("module.lib_depends"); + static const std::string s("module.vendor"); return s; } -const std::string& Module::PROP_VERSION() + +const std::string&Module::PROP_DESCRIPTION() { - static const std::string s("module.version"); + static const std::string s("module.description"); + return s; +} + +const std::string&Module::PROP_AUTOLOAD_DIR() +{ + static const std::string s("module.autoload_dir"); return s; } Module::Module() : d(0) { } Module::~Module() { delete d; } void Module::Init(CoreModuleContext* coreCtx, ModuleInfo* info) { ModulePrivate* mp = new ModulePrivate(this, coreCtx, info); std::swap(mp, d); delete mp; } void Module::Uninit() { if (d->moduleContext) { delete d->moduleContext; d->moduleContext = 0; } d->moduleActivator = 0; } bool Module::IsLoaded() const { return d->moduleContext != 0; } void Module::Start() { if (d->moduleContext) { US_WARN << "Module " << d->info.name << " already started."; return; } d->moduleContext = new ModuleContext(this->d); // try // { d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADING, this)); // try to get a ModuleActivator instance if (d->info.activatorHook) { try { d->moduleActivator = d->info.activatorHook(); } catch (...) { US_ERROR << "Creating the module activator of " << d->info.name << " failed"; throw; } d->moduleActivator->Load(d->moduleContext); } d->StartStaticModules(); #ifdef US_ENABLE_AUTOLOADING_SUPPORT if (ModuleSettings::IsAutoLoadingEnabled()) { AutoLoadModules(d->info); } #endif d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADED, this)); // } // catch (...) // { // d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); // d->RemoveModuleResources(); // delete d->moduleContext; // d->moduleContext = 0; // d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); // US_ERROR << "Calling the module activator Load() method of " << d->info.name << " failed!"; // throw; // } } void Module::Stop() { if (d->moduleContext == 0) { US_WARN << "Module " << d->info.name << " already stopped."; return; } try { d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); d->StopStaticModules(); if (d->moduleActivator) { d->moduleActivator->Unload(d->moduleContext); } } catch (...) { US_WARN << "Calling the module activator Unload() method of " << d->info.name << " failed!"; try { d->RemoveModuleResources(); } catch (...) {} delete d->moduleContext; d->moduleContext = 0; d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); throw; } d->RemoveModuleResources(); delete d->moduleContext; d->moduleContext = 0; d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); } ModuleContext* Module::GetModuleContext() const { return d->moduleContext; } long Module::GetModuleId() const { return d->info.id; } std::string Module::GetLocation() const { return d->info.location; } std::string Module::GetName() const { return d->info.name; } ModuleVersion Module::GetVersion() const { return d->version; } -std::string Module::GetProperty(const std::string& key) const +Any Module::GetProperty(const std::string& key) const { - if (d->properties.count(key) == 0) return ""; - return d->properties[key]; + return d->moduleManifest.GetValue(key); +} + +std::vector Module::GetPropertyKeys() const +{ + return d->moduleManifest.GetKeys(); +} + +std::vector Module::GetRegisteredServices() const +{ + std::vector sr; + std::vector res; + d->coreCtx->services.GetRegisteredByModule(d, sr); + for (std::vector::const_iterator i = sr.begin(); + i != sr.end(); ++i) + { + res.push_back(i->GetReference()); + } + return res; +} + +std::vector Module::GetServicesInUse() const +{ + std::vector sr; + std::vector res; + d->coreCtx->services.GetUsedByModule(const_cast(this), sr); + for (std::vector::const_iterator i = sr.begin(); + i != sr.end(); ++i) + { + res.push_back(i->GetReference()); + } + return res; } ModuleResource Module::GetResource(const std::string& path) const { if (d->resourceTreePtrs.empty()) { return ModuleResource(); } for (std::size_t i = 0; i < d->resourceTreePtrs.size(); ++i) { if (!d->resourceTreePtrs[i]->IsValid()) continue; ModuleResource result(path, d->resourceTreePtrs[i], d->resourceTreePtrs); if (result) return result; } return ModuleResource(); } std::vector Module::FindResources(const std::string& path, const std::string& filePattern, bool recurse) const { std::vector result; if (d->resourceTreePtrs.empty()) return result; for (std::size_t i = 0; i < d->resourceTreePtrs.size(); ++i) { if (!d->resourceTreePtrs[i]->IsValid()) continue; std::vector nodes; d->resourceTreePtrs[i]->FindNodes(path, filePattern, recurse, nodes); for (std::vector::iterator nodeIter = nodes.begin(); nodeIter != nodes.end(); ++nodeIter) { result.push_back(ModuleResource(*nodeIter, d->resourceTreePtrs[i], d->resourceTreePtrs)); } } return result; } US_END_NAMESPACE US_USE_NAMESPACE std::ostream& operator<<(std::ostream& os, const Module& module) { os << "Module[" << "id=" << module.GetModuleId() << ", loc=" << module.GetLocation() << ", name=" << module.GetName() << "]"; return os; } std::ostream& operator<<(std::ostream& os, Module const * module) { return operator<<(os, *module); } diff --git a/Core/Code/CppMicroServices/src/module/usModule.h b/Core/CppMicroServices/src/module/usModule.h similarity index 72% rename from Core/Code/CppMicroServices/src/module/usModule.h rename to Core/CppMicroServices/src/module/usModule.h index de8aede10f..b92e2239cb 100644 --- a/Core/Code/CppMicroServices/src/module/usModule.h +++ b/Core/CppMicroServices/src/module/usModule.h @@ -1,267 +1,368 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULE_H #define USMODULE_H #include "usModuleVersion.h" #include US_BEGIN_NAMESPACE +class Any; class CoreModuleContext; struct ModuleInfo; class ModuleContext; class ModuleResource; class ModulePrivate; +template +class ServiceReference; + +typedef ServiceReference ServiceReferenceU; + /** * \ingroup MicroServices * * Represents a CppMicroServices module. * *

* A %Module object is the access point to a CppMicroServices module. * Each CppMicroServices module has an associated %Module object. * *

* A module has unique identity, a long, chosen by the * framework. This identity does not change during the lifecycle of a module. * *

* A module can be in one of two states: *

    *
  • LOADED *
  • UNLOADED *
*

* You can determine the current state by using IsLoaded(). * *

* A module can only execute code when its state is LOADED. * An UNLOADED module is a * zombie and can only be reached because it was loaded before. However, * unloaded modules can be loaded again. * *

* The framework is the only entity that is allowed to create * %Module objects. * * @remarks This class is thread safe. */ class US_EXPORT Module { public: + /** + * Returns the property key for looking up this module's id. + * The property value is of type \c long. + * + * @return The id property key. + */ static const std::string& PROP_ID(); + + /** + * Returns the property key for looking up this module's name. + * The property value is of type \c std::string. + * + * @return The name property key. + */ static const std::string& PROP_NAME(); + + /** + * Returns the property key for looking up this module's + * location the file system. + * The property value is of type \c std::string. + * + * @return The location property key. + */ static const std::string& PROP_LOCATION(); - static const std::string& PROP_MODULE_DEPENDS(); - static const std::string& PROP_LIB_DEPENDS(); + + /** + * Returns the property key with a value of \c module.version for looking + * up this module's version identifier. + * The property value is of type \c std::string. + * + * @return The version property key. + */ static const std::string& PROP_VERSION(); + /** + * Returns the property key with a value of \c module.vendor for looking + * up this module's vendor information. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_VENDOR(); + + /** + * Returns the property key with a value of \c module.description for looking + * up this module's description. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_DESCRIPTION(); + + /** + * Returns the property key with a value of \c module.autoload_dir for looking + * up this module's auto-load directory. + * The property value is of type \c std::string. + * + * @return The version property key. + */ + static const std::string& PROP_AUTOLOAD_DIR(); + ~Module(); /** * Returns this module's current state. * *

* A module can be in only one state at any time. * * @return true if the module is LOADED * false if it is UNLOADED */ bool IsLoaded() const; /** * Returns this module's {@link ModuleContext}. The returned * ModuleContext can be used by the caller to act on behalf * of this module. * *

* If this module is not in the LOADED state, then this * module has no valid ModuleContext. This method will * return 0 if this module has no valid * ModuleContext. * * @return A ModuleContext for this module or * 0 if this module has no valid * ModuleContext. */ ModuleContext* GetModuleContext() const; /** * Returns this module's unique identifier. This module is assigned a unique * identifier by the framework when it was loaded. * *

* A module's unique identifier has the following attributes: *

    *
  • Is unique. *
  • Is a long. *
  • Its value is not reused for another module, even after a module is * unloaded. *
  • Does not change while a module remains loaded. *
  • Does not change when a module is reloaded. *
* *

* This method continues to return this module's unique identifier while * this module is in the UNLOADED state. * * @return The unique identifier of this module. */ long GetModuleId() const; /** * Returns this module's location. * *

* The location is the full path to the module's shared library. * This method continues to return this module's location * while this module is in the UNLOADED state. * * @return The string representation of this module's location. */ std::string GetLocation() const; /** * Returns the name of this module as specified by the * US_CREATE_MODULE CMake macro. The module * name together with a version must identify a unique module. * *

* This method continues to return this module's name while * this module is in the UNLOADED state. * * @return The name of this module. */ std::string GetName() const; /** * Returns the version of this module as specified by the * US_INITIALIZE_MODULE CMake macro. If this module does not have a * specified version then {@link ModuleVersion::EmptyVersion} is returned. * *

* This method continues to return this module's version while * this module is in the UNLOADED state. * * @return The version of this module. */ ModuleVersion GetVersion() const; /** * Returns the value of the specified property for this module. The - * method returns an empty string if the property is not found. + * method returns an empty Any if the property is not found. * * @param key The name of the requested property. * @return The value of the requested property, or an empty string * if the property is undefined. + * + * @sa GetPropertyKeys() + * @sa \ref MicroServices_ModuleProperties + */ + Any GetProperty(const std::string& key) const; + + /** + * Returns a list of top-level property keys for this module. + * + * @return A list of available property keys. + * + * @sa \ref MicroServices_ModuleProperties + */ + std::vector GetPropertyKeys() const; + + /** + * Returns this module's ServiceReference list for all services it + * has registered or an empty list if this module has no registered + * services. + * + * The list is valid at the time of the call to this method, however, + * as the framework is a very dynamic environment, services can be + * modified or unregistered at anytime. + * + * @return A list of ServiceReference objects for services this + * module has registered. + */ + std::vector GetRegisteredServices() const; + + /** + * Returns this module's ServiceReference list for all services it is + * using or returns an empty list if this module is not using any + * services. A module is considered to be using a service if its use + * count for that service is greater than zero. + * + * The list is valid at the time of the call to this method, however, + * as the framework is a very dynamic environment, services can be + * modified or unregistered at anytime. + * + * @return A list of ServiceReference objects for all services this + * module is using. */ - std::string GetProperty(const std::string& key) const; + std::vector GetServicesInUse() const; /** * Returns the resource at the specified \c path in this module. * The specified \c path is always relative to the root of this module and may * begin with '/'. A path value of "/" indicates the root of this module. * * \note In case of other modules being statically linked into this module, * the \c path can be ambiguous and returns the first resource matching the * provided \c path according to the order of the static module names in the * #US_LOAD_IMPORTED_MODULES macro. * * @param path The path name of the resource. * @return A ModuleResource object for the given \c path. If the \c path cannot * be found in this module or the module's state is \c UNLOADED, an invalid * ModuleResource object is returned. */ ModuleResource GetResource(const std::string& path) const; /** * Returns resources in this module and its statically linked modules. * * This method is intended to be used to obtain configuration, setup, localization * and other information from this module. * * This method can either return only resources in the specified \c path or recurse * into subdirectories returning resources in the directory tree beginning at the * specified path. * * Examples: * \snippet uServices-resources/main.cpp 0 * * \note In case of modules statically linked into this module, the returned * ModuleResource objects can represent the same resource path, coming from * different static modules. The order of the ModuleResource objects in the * returned container matches the order of the static module names in the * #US_LOAD_IMPORTED_MODULES macro. * * @param path The path name in which to look. The path is always relative to the root * of this module and may begin with '/'. A path value of "/" indicates the root of this module. * @param filePattern The resource name pattern for selecting entries in the specified path. * The pattern is only matched against the last element of the resource path. Substring * matching is supported using the wildcard charachter ('*'). If \c filePattern is empty, * this is equivalent to "*" and matches all resources. * @param recurse If \c true, recurse into subdirectories. Otherwise only return resources * from the specified path. * @return A vector of ModuleResource objects for each matching entry. The objects are sorted * such that resources from this module are returned first followed by the resources from * statically linked modules in the load order as specified in #US_LOAD_IMPORTED_MODULES. */ std::vector FindResources(const std::string& path, const std::string& filePattern, bool recurse) const; private: friend class ModuleRegistry; friend class ServiceReferencePrivate; ModulePrivate* d; Module(); void Init(CoreModuleContext* coreCtx, ModuleInfo* info); void Uninit(); void Start(); void Stop(); // purposely not implemented Module(const Module &); Module& operator=(const Module&); }; US_END_NAMESPACE /** * \ingroup MicroServices */ US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(Module)& module); /** * \ingroup MicroServices */ US_EXPORT std::ostream& operator<<(std::ostream& os, US_PREPEND_NAMESPACE(Module) const * module); #endif // USMODULE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp b/Core/CppMicroServices/src/module/usModuleAbstractTracked.tpp similarity index 73% rename from Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp rename to Core/CppMicroServices/src/module/usModuleAbstractTracked.tpp index d344538f03..66187162a2 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp +++ b/Core/CppMicroServices/src/module/usModuleAbstractTracked.tpp @@ -1,314 +1,315 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include US_BEGIN_NAMESPACE -template -const bool ModuleAbstractTracked::DEBUG_OUTPUT = false; +template +const bool ModuleAbstractTracked::DEBUG_OUTPUT = false; -template -ModuleAbstractTracked::ModuleAbstractTracked() +template +ModuleAbstractTracked::ModuleAbstractTracked() { closed = false; } -template -ModuleAbstractTracked::~ModuleAbstractTracked() +template +ModuleAbstractTracked::~ModuleAbstractTracked() { } -template -void ModuleAbstractTracked::SetInitial(const std::list& initiallist) +template +void ModuleAbstractTracked::SetInitial(const std::vector& initiallist) { - initial = initiallist; + std::copy(initiallist.begin(), initiallist.end(), std::back_inserter(initial)); if (DEBUG_OUTPUT) { - for(typename std::list::const_iterator item = initiallist.begin(); - item != initiallist.end(); ++item) + for(typename std::list::const_iterator item = initial.begin(); + item != initial.end(); ++item) { US_DEBUG << "ModuleAbstractTracked::setInitial: " << (*item); } } } -template -void ModuleAbstractTracked::TrackInitial() +template +void ModuleAbstractTracked::TrackInitial() { while (true) { - S item(0); + S item; { typename Self::Lock l(this); if (closed || (initial.size() == 0)) { /* * if there are no more initial items */ return; /* we are done */ } /* * move the first item from the initial list to the adding list * within this synchronized block. */ item = initial.front(); initial.pop_front(); - if (tracked[item]) + if (TTT::IsValid(tracked[item])) { /* if we are already tracking this item */ US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackInitial[already tracked]: " << item; continue; /* skip this item */ } if (std::find(adding.begin(), adding.end(), item) != adding.end()) { /* * if this item is already in the process of being added. */ US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackInitial[already adding]: " << item; continue; /* skip this item */ } adding.push_back(item); } US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackInitial: " << item; TrackAdding(item, R()); /* * Begin tracking it. We call trackAdding * since we have already put the item in the * adding list. */ } } -template -void ModuleAbstractTracked::Close() +template +void ModuleAbstractTracked::Close() { closed = true; } -template -void ModuleAbstractTracked::Track(S item, R related) +template +void ModuleAbstractTracked::Track(S item, R related) { - T object(0); + T object = TTT::DefaultValue(); { typename Self::Lock l(this); if (closed) { return; } object = tracked[item]; - if (!object) + if (!TTT::IsValid(object)) { /* we are not tracking the item */ if (std::find(adding.begin(), adding.end(),item) != adding.end()) { /* if this item is already in the process of being added. */ US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::track[already adding]: " << item; return; } adding.push_back(item); /* mark this item is being added */ } else { /* we are currently tracking this item */ US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::track[modified]: " << item; Modified(); /* increment modification count */ } } - if (!object) + if (!TTT::IsValid(object)) { /* we are not tracking the item */ TrackAdding(item, related); } else { /* Call customizer outside of synchronized region */ CustomizerModified(item, related, object); /* * If the customizer throws an unchecked exception, it is safe to * let it propagate */ } } -template -void ModuleAbstractTracked::Untrack(S item, R related) +template +void ModuleAbstractTracked::Untrack(S item, R related) { - T object(0); + T object = TTT::DefaultValue(); { typename Self::Lock l(this); std::size_t initialSize = initial.size(); initial.remove(item); if (initialSize != initial.size()) { /* if this item is already in the list * of initial references to process */ US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::untrack[removed from initial]: " << item; return; /* we have removed it from the list and it will not be * processed */ } std::size_t addingSize = adding.size(); adding.remove(item); if (addingSize != adding.size()) { /* if the item is in the process of * being added */ US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::untrack[being added]: " << item; return; /* * in case the item is untracked while in the process of * adding */ } object = tracked[item]; /* * must remove from tracker before * calling customizer callback */ tracked.erase(item); - if (!object) + if (!TTT::IsValid(object)) { /* are we actually tracking the item */ return; } Modified(); /* increment modification count */ } US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::untrack[removed]: " << item; /* Call customizer outside of synchronized region */ CustomizerRemoved(item, related, object); /* * If the customizer throws an unchecked exception, it is safe to let it * propagate */ } -template -std::size_t ModuleAbstractTracked::Size() const +template +std::size_t ModuleAbstractTracked::Size() const { return tracked.size(); } -template -bool ModuleAbstractTracked::IsEmpty() const +template +bool ModuleAbstractTracked::IsEmpty() const { return tracked.empty(); } -template -T ModuleAbstractTracked::GetCustomizedObject(S item) const +template +typename ModuleAbstractTracked::T +ModuleAbstractTracked::GetCustomizedObject(S item) const { typename TrackingMap::const_iterator i = tracked.find(item); if (i != tracked.end()) return i->second; return T(); } -template -void ModuleAbstractTracked::GetTracked(std::list& items) const +template +void ModuleAbstractTracked::GetTracked(std::vector& items) const { for (typename TrackingMap::const_iterator i = tracked.begin(); i != tracked.end(); ++i) { items.push_back(i->first); } } -template -void ModuleAbstractTracked::Modified() +template +void ModuleAbstractTracked::Modified() { trackingCount.Ref(); } -template -int ModuleAbstractTracked::GetTrackingCount() const +template +int ModuleAbstractTracked::GetTrackingCount() const { return trackingCount; } -template -void ModuleAbstractTracked::CopyEntries(TrackingMap& map) const +template +void ModuleAbstractTracked::CopyEntries(TrackingMap& map) const { map.insert(tracked.begin(), tracked.end()); } -template -bool ModuleAbstractTracked::CustomizerAddingFinal(S item, const T& custom) +template +bool ModuleAbstractTracked::CustomizerAddingFinal(S item, const T& custom) { typename Self::Lock l(this); std::size_t addingSize = adding.size(); adding.remove(item); if (addingSize != adding.size() && !closed) { /* * if the item was not untracked during the customizer * callback */ - if (custom) + if (TTT::IsValid(custom)) { tracked[item] = custom; Modified(); /* increment modification count */ this->NotifyAll(); /* notify any waiters */ } return false; } else { return true; } } -template -void ModuleAbstractTracked::TrackAdding(S item, R related) +template +void ModuleAbstractTracked::TrackAdding(S item, R related) { US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackAdding:" << item; - T object(0); + T object = TTT::DefaultValue(); bool becameUntracked = false; /* Call customizer outside of synchronized region */ try { object = CustomizerAdding(item, related); becameUntracked = this->CustomizerAddingFinal(item, object); } catch (...) { /* * If the customizer throws an exception, it will * propagate after the cleanup code. */ this->CustomizerAddingFinal(item, object); throw; } /* * The item became untracked during the customizer callback. */ - if (becameUntracked && object) + if (becameUntracked && TTT::IsValid(object)) { US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackAdding[removed]: " << item; /* Call customizer outside of synchronized region */ CustomizerRemoved(item, related, object); /* * If the customizer throws an unchecked exception, it is safe to * let it propagate */ } } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h b/Core/CppMicroServices/src/module/usModuleAbstractTracked_p.h similarity index 96% rename from Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h rename to Core/CppMicroServices/src/module/usModuleAbstractTracked_p.h index ccdc3627d4..9bdb4f157b 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h +++ b/Core/CppMicroServices/src/module/usModuleAbstractTracked_p.h @@ -1,291 +1,293 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEABSTRACTTRACKED_H #define USMODULEABSTRACTTRACKED_H -#include +#include #include "usAtomicInt_p.h" #include "usAny.h" US_BEGIN_NAMESPACE /** * This class is not intended to be used directly. It is exported to support * the CppMicroServices module system. * * Abstract class to track items. If a Tracker is reused (closed then reopened), * then a new ModuleAbstractTracked object is used. This class acts as a map of tracked * item -> customized object. Subclasses of this class will act as the listener * object for the tracker. This class is used to synchronize access to the * tracked items. This is not a public class. It is only for use by the * implementation of the Tracker class. * * @tparam S The tracked item. It is the key. * @tparam T The value mapped to the tracked item. * @tparam R The reason the tracked item is being tracked or untracked. * @ThreadSafe */ -template -class ModuleAbstractTracked : public US_DEFAULT_THREADING > +template +class ModuleAbstractTracked : public US_DEFAULT_THREADING > { public: + typedef typename TTT::TrackedType T; + /* set this to true to compile in debug messages */ static const bool DEBUG_OUTPUT; // = false; typedef std::map TrackingMap; /** * ModuleAbstractTracked constructor. */ ModuleAbstractTracked(); virtual ~ModuleAbstractTracked(); /** * Set initial list of items into tracker before events begin to be * received. * * This method must be called from Tracker's open method while synchronized * on this object in the same synchronized block as the add listener call. * * @param list The initial list of items to be tracked. null * entries in the list are ignored. * @GuardedBy this */ - void SetInitial(const std::list& list); + void SetInitial(const std::vector& list); /** * Track the initial list of items. This is called after events can begin to * be received. * * This method must be called from Tracker's open method while not * synchronized on this object after the add listener call. * */ void TrackInitial(); /** * Called by the owning Tracker object when it is closed. */ void Close(); /** * Begin to track an item. * * @param item S to be tracked. * @param related Action related object. */ void Track(S item, R related); /** * Discontinue tracking the item. * * @param item S to be untracked. * @param related Action related object. */ void Untrack(S item, R related); /** * Returns the number of tracked items. * * @return The number of tracked items. * * @GuardedBy this */ std::size_t Size() const; /** * Returns if the tracker is empty. * * @return Whether the tracker is empty. * * @GuardedBy this */ bool IsEmpty() const; /** * Return the customized object for the specified item * * @param item The item to lookup in the map * @return The customized object for the specified item. * * @GuardedBy this */ T GetCustomizedObject(S item) const; /** * Return the list of tracked items. * * @return The tracked items. * @GuardedBy this */ - void GetTracked(std::list& items) const; + void GetTracked(std::vector& items) const; /** * Increment the modification count. If this method is overridden, the * overriding method MUST call this method to increment the tracking count. * * @GuardedBy this */ virtual void Modified(); /** * Returns the tracking count for this ServiceTracker object. * * The tracking count is initialized to 0 when this object is opened. Every * time an item is added, modified or removed from this object the tracking * count is incremented. * * @GuardedBy this * @return The tracking count for this object. */ int GetTrackingCount() const; /** * Copy the tracked items and associated values into the specified map. * * @param map The map into which to copy the tracked items and associated * values. This map must not be a user provided map so that user code * is not executed while synchronized on this. * @return The specified map. * @GuardedBy this */ void CopyEntries(TrackingMap& map) const; /** * Call the specific customizer adding method. This method must not be * called while synchronized on this object. * * @param item S to be tracked. * @param related Action related object. * @return Customized object for the tracked item or null if * the item is not to be tracked. */ virtual T CustomizerAdding(S item, const R& related) = 0; /** * Call the specific customizer modified method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ virtual void CustomizerModified(S item, const R& related, T object) = 0; /** * Call the specific customizer removed method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ virtual void CustomizerRemoved(S item, const R& related, T object) = 0; /** * List of items in the process of being added. This is used to deal with * nesting of events. Since events may be synchronously delivered, events * can be nested. For example, when processing the adding of a service and * the customizer causes the service to be unregistered, notification to the * nested call to untrack that the service was unregistered can be made to * the track method. * * Since the std::vector implementation is not synchronized, all access to * this list must be protected by the same synchronized object for * thread-safety. * * @GuardedBy this */ std::list adding; /** * true if the tracked object is closed. * * This field is volatile because it is set by one thread and read by * another. */ volatile bool closed; /** * Initial list of items for the tracker. This is used to correctly process * the initial items which could be modified before they are tracked. This * is necessary since the initial set of tracked items are not "announced" * by events and therefore the event which makes the item untracked could be * delivered before we track the item. * * An item must not be in both the initial and adding lists at the same * time. An item must be moved from the initial list to the adding list * "atomically" before we begin tracking it. * * Since the LinkedList implementation is not synchronized, all access to * this list must be protected by the same synchronized object for * thread-safety. * * @GuardedBy this */ std::list initial; /** * Common logic to add an item to the tracker used by track and * trackInitial. The specified item must have been placed in the adding list * before calling this method. * * @param item S to be tracked. * @param related Action related object. */ void TrackAdding(S item, R related); private: - typedef ModuleAbstractTracked Self; + typedef ModuleAbstractTracked Self; /** * Map of tracked items to customized objects. * * @GuardedBy this */ TrackingMap tracked; /** * Modification count. This field is initialized to zero and incremented by * modified. * * @GuardedBy this */ AtomicInt trackingCount; bool CustomizerAddingFinal(S item, const T& custom); }; US_END_NAMESPACE #include "usModuleAbstractTracked.tpp" #endif // USMODULEABSTRACTTRACKED_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleActivator.h b/Core/CppMicroServices/src/module/usModuleActivator.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleActivator.h rename to Core/CppMicroServices/src/module/usModuleActivator.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleContext.cpp b/Core/CppMicroServices/src/module/usModuleContext.cpp similarity index 72% rename from Core/Code/CppMicroServices/src/module/usModuleContext.cpp rename to Core/CppMicroServices/src/module/usModuleContext.cpp index 2164370632..de01d5658e 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleContext.cpp +++ b/Core/CppMicroServices/src/module/usModuleContext.cpp @@ -1,157 +1,161 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include "usModuleContext.h" #include "usModuleRegistry.h" #include "usModulePrivate.h" #include "usCoreModuleContext_p.h" #include "usServiceRegistry_p.h" -#include "usServiceReferencePrivate.h" +#include "usServiceReferenceBasePrivate.h" US_BEGIN_NAMESPACE class ModuleContextPrivate { public: ModuleContextPrivate(ModulePrivate* module) : module(module) {} ModulePrivate* module; }; ModuleContext::ModuleContext(ModulePrivate* module) : d(new ModuleContextPrivate(module)) {} ModuleContext::~ModuleContext() { delete d; } Module* ModuleContext::GetModule() const { return d->module->q; } Module* ModuleContext::GetModule(long id) const { return ModuleRegistry::GetModule(id); } void ModuleContext::GetModules(std::vector& modules) const { ModuleRegistry::GetModules(modules); } -ServiceRegistration ModuleContext::RegisterService(const std::list& clazzes, - US_BASECLASS_NAME* service, - const ServiceProperties& properties) +ServiceRegistrationU ModuleContext::RegisterService(const InterfaceMap& service, + const ServiceProperties& properties) { - return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); + return d->module->coreCtx->services.RegisterService(d->module, service, properties); } -ServiceRegistration ModuleContext::RegisterService(const char* clazz, US_BASECLASS_NAME* service, - const ServiceProperties& properties) +std::vector ModuleContext::GetServiceReferences(const std::string& clazz, + const std::string& filter) { - std::list clazzes; - clazzes.push_back(clazz); - return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); + std::vector result; + std::vector refs; + d->module->coreCtx->services.Get(clazz, filter, d->module, refs); + for (std::vector::const_iterator iter = refs.begin(); + iter != refs.end(); ++iter) + { + result.push_back(ServiceReferenceU(*iter)); + } + return result; } -std::list ModuleContext::GetServiceReferences(const std::string& clazz, - const std::string& filter) +ServiceReferenceU ModuleContext::GetServiceReference(const std::string& clazz) { - std::list result; - d->module->coreCtx->services.Get(clazz, filter, 0, result); - return result; + return d->module->coreCtx->services.Get(d->module, clazz); } -ServiceReference ModuleContext::GetServiceReference(const std::string& clazz) +void* ModuleContext::GetService(const ServiceReferenceBase& reference) { - return d->module->coreCtx->services.Get(d->module, clazz); + if (!reference) + { + throw std::invalid_argument("Default constructed ServiceReference is not a valid input to GetService()"); + } + return reference.d->GetService(d->module->q); } -US_BASECLASS_NAME* ModuleContext::GetService(const ServiceReference& reference) +InterfaceMap ModuleContext::GetService(const ServiceReferenceU& reference) { if (!reference) { - throw std::invalid_argument("Default constructed ServiceReference is not a valid input to getService()"); + throw std::invalid_argument("Default constructed ServiceReference is not a valid input to GetService()"); } - ServiceReference internalRef(reference); - return internalRef.d->GetService(d->module->q); + return reference.d->GetServiceInterfaceMap(d->module->q); } -bool ModuleContext::UngetService(const ServiceReference& reference) +bool ModuleContext::UngetService(const ServiceReferenceBase& reference) { - ServiceReference ref = reference; + ServiceReferenceBase ref = reference; return ref.d->UngetService(d->module->q, true); } void ModuleContext::AddServiceListener(const ServiceListener& delegate, const std::string& filter) { d->module->coreCtx->listeners.AddServiceListener(this, delegate, NULL, filter); } void ModuleContext::RemoveServiceListener(const ServiceListener& delegate) { d->module->coreCtx->listeners.RemoveServiceListener(this, delegate, NULL); } void ModuleContext::AddModuleListener(const ModuleListener& delegate) { d->module->coreCtx->listeners.AddModuleListener(this, delegate, NULL); } void ModuleContext::RemoveModuleListener(const ModuleListener& delegate) { d->module->coreCtx->listeners.RemoveModuleListener(this, delegate, NULL); } void ModuleContext::AddServiceListener(const ServiceListener& delegate, void* data, const std::string &filter) { d->module->coreCtx->listeners.AddServiceListener(this, delegate, data, filter); } void ModuleContext::RemoveServiceListener(const ServiceListener& delegate, void* data) { d->module->coreCtx->listeners.RemoveServiceListener(this, delegate, data); } void ModuleContext::AddModuleListener(const ModuleListener& delegate, void* data) { d->module->coreCtx->listeners.AddModuleListener(this, delegate, data); } void ModuleContext::RemoveModuleListener(const ModuleListener& delegate, void* data) { d->module->coreCtx->listeners.RemoveModuleListener(this, delegate, data); } US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/module/usModuleContext.h b/Core/CppMicroServices/src/module/usModuleContext.h similarity index 67% rename from Core/Code/CppMicroServices/src/module/usModuleContext.h rename to Core/CppMicroServices/src/module/usModuleContext.h index 0138a27842..0ec6aaaabb 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleContext.h +++ b/Core/CppMicroServices/src/module/usModuleContext.h @@ -1,649 +1,831 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULECONTEXT_H_ #define USMODULECONTEXT_H_ +// TODO: Replace includes with forward directives! + #include "usUtils_p.h" #include "usServiceInterface.h" #include "usServiceEvent.h" #include "usServiceRegistration.h" #include "usServiceException.h" #include "usModuleEvent.h" US_BEGIN_NAMESPACE typedef US_SERVICE_LISTENER_FUNCTOR ServiceListener; typedef US_MODULE_LISTENER_FUNCTOR ModuleListener; class ModuleContextPrivate; +class ServiceFactory; + +template class ServiceObjects; /** * \ingroup MicroServices * * A module's execution context within the framework. The context is used to * grant access to other methods so that this module can interact with the * Micro Services Framework. * *

* ModuleContext methods allow a module to: *

    *
  • Subscribe to events published by the framework. *
  • Register service objects with the framework service registry. *
  • Retrieve ServiceReferences from the framework service * registry. *
  • Get and release service objects for a referenced service. *
  • Get the list of modules loaded in the framework. *
  • Get the {@link Module} object for a module. *
* *

* A ModuleContext object will be created and provided to the * module associated with this context when it is loaded using the * {@link ModuleActivator::Load} method. The same ModuleContext * object will be passed to the module associated with this context when it is * unloaded using the {@link ModuleActivator::Unload} method. A * ModuleContext object is generally for the private use of its * associated module and is not meant to be shared with other modules in the * module environment. * *

* The Module object associated with a ModuleContext * object is called the context module. * *

* The ModuleContext object is only valid during the execution of * its context module; that is, during the period when the context module * is loaded. If the ModuleContext * object is used subsequently, a std::logic_error is * thrown. The ModuleContext object is never reused after * its context module is unloaded. * *

* The framework is the only entity that can create ModuleContext * objects. * * @remarks This class is thread safe. */ class US_EXPORT ModuleContext { public: ~ModuleContext(); /** * Returns the Module object associated with this * ModuleContext. This module is called the context module. * * @return The Module object associated with this * ModuleContext. * @throws std::logic_error If this ModuleContext is no * longer valid. */ Module* GetModule() const; /** * Returns the module with the specified identifier. * * @param id The identifier of the module to retrieve. * @return A Module object or 0 if the * identifier does not match any previously loaded module. */ Module* GetModule(long id) const; /** * Returns a list of all known modules. *

* This method returns a list of all modules loaded in the module * environment at the time of the call to this method. This list will * also contain modules which might already have been unloaded. * * @param modules A std::vector of Module objects which * will hold one object per known module. */ void GetModules(std::vector& modules) const; /** * Registers the specified service object with the specified properties * under the specified class names into the framework. A * ServiceRegistration object is returned. The * ServiceRegistration object is for the private use of the * module registering the service and should not be shared with other * modules. The registering module is defined to be the context module. * Other modules can locate the service by using either the * {@link #GetServiceReferences} or {@link #GetServiceReference} method. * *

* A module can register a service object that implements the - * {@link ServiceFactory} interface to have more flexibility in providing - * service objects to other modules. + * ServiceFactory or PrototypeServiceFactory interface to have more + * flexibility in providing service objects to other modules. * *

* The following steps are taken when registering a service: *

    *
  1. The framework adds the following service properties to the service * properties from the specified ServiceProperties (which may be * omitted):
    * A property named ServiceConstants#SERVICE_ID() identifying the * registration number of the service
    * A property named ServiceConstants#OBJECTCLASS() containing all the * specified classes.
    + * A property named ServiceConstants#SERVICE_SCOPE() identifying the scope + * of the service.
    * Properties with these names in the specified ServiceProperties will * be ignored. *
  2. The service is added to the framework service registry and may now be * used by other modules. *
  3. A service event of type ServiceEvent#REGISTERED is fired. *
  4. A ServiceRegistration object for this registration is * returned. *
* - * @param clazzes The class names under which the service can be located. - * The class names will be stored in the service's - * properties under the key ServiceConstants#OBJECTCLASS(). - * @param service The service object or a ServiceFactory - * object. + * @note This is a low-level method and should normally not be used directly. + * Use one of the templated RegisterService methods instead. + * + * @param service The service object, which is a map of interface identifiers + * to raw service pointers. * @param properties The properties for this service. The keys in the * properties object must all be std::string objects. See * {@link ServiceConstants} for a list of standard service property keys. * Changes should not be made to this object after calling this * method. To update the service's properties the * {@link ServiceRegistration::SetProperties} method must be called. * The set of properties may be omitted if the service has * no properties. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. + * * @throws std::invalid_argument If one of the following is true: *
    *
  • service is 0. *
  • properties contains case variants of the same key name. *
* @throws std::logic_error If this ModuleContext is no longer valid. + * * @see ServiceRegistration * @see ServiceFactory + * @see PrototypeServiceFactory */ - ServiceRegistration RegisterService(const std::list& clazzes, - US_BASECLASS_NAME* service, - const ServiceProperties& properties = ServiceProperties()); + ServiceRegistrationU RegisterService(const InterfaceMap& service, + const ServiceProperties& properties = ServiceProperties()); /** * Registers the specified service object with the specified properties - * under the specified class name with the framework. + * using the specified template argument with the framework. * *

- * This method is otherwise identical to - * RegisterService(const std:list<std::string>&, us::Base*, const ServiceProperties&) - * and is provided as a convenience when service will only be registered under a single - * class name. Note that even in this case the value of the service's - * ServiceConstants::OBJECTCLASS property will be a std::list, rather - * than just a single string. + * This method is provided as a convenience when service will only be registered under + * a single class name whose type is available to the caller. It is otherwise identical to + * RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred + * since it avoids errors in the string literal identifying the class name or interface identifier. + * + * Example usage: + * \snippet uServices-registration/main.cpp 1-1 + * \snippet uServices-registration/main.cpp 1-2 * - * @param clazz The class name under which the service can be located. + * @tparam S The type under which the service can be located. * @param service The service object or a ServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. - * @see RegisterService(const std:list<std::string>&, us::Base*, const ServiceProperties&) + * @throws ServiceException If the service type \c S is invalid or the + * \c service object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ - ServiceRegistration RegisterService(const char* clazz, US_BASECLASS_NAME* service, - const ServiceProperties& properties = ServiceProperties()); + template + ServiceRegistration RegisterService(S* service, const ServiceProperties& properties = ServiceProperties()) + { + InterfaceMap servicePointers = MakeInterfaceMap(service); + return RegisterService(servicePointers, properties); + } /** * Registers the specified service object with the specified properties * using the specified template argument with the framework. * *

- * This method is provided as a convenience when service will only be registered under + * This method is provided as a convenience when registering a service under + * two interface classes whose type is available to the caller. It is otherwise identical to + * RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred + * since it avoids errors in the string literal identifying the class name or interface identifier. + * + * Example usage: + * \snippet uServices-registration/main.cpp 2-1 + * \snippet uServices-registration/main.cpp 2-2 + * + * @tparam I1 The first interface type under which the service can be located. + * @tparam I2 The second interface type under which the service can be located. + * @param impl The service object or a ServiceFactory object. + * @param properties The properties for this service. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws ServiceException If the service type \c S is invalid or the + * \c service object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) + */ + template + ServiceRegistration RegisterService(Impl* impl, const ServiceProperties& properties = ServiceProperties()) + { + InterfaceMap servicePointers = MakeInterfaceMap(impl); + return RegisterService(servicePointers, properties); + } + + /** + * Registers the specified service object with the specified properties + * using the specified template argument with the framework. + * + *

+ * This method is identical to the RegisterService(Impl*, const ServiceProperties&) + * method except that it supports three service interface types. + * + * @tparam I1 The first interface type under which the service can be located. + * @tparam I2 The second interface type under which the service can be located. + * @tparam I3 The third interface type under which the service can be located. + * @param impl The service object or a ServiceFactory object. + * @param properties The properties for this service. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws ServiceException If the service type \c S is invalid or the + * \c service object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) + */ + template + ServiceRegistration RegisterService(Impl* impl, const ServiceProperties& properties = ServiceProperties()) + { + InterfaceMap servicePointers = MakeInterfaceMap(impl); + return RegisterService(servicePointers, properties); + } + + /** + * Registers the specified service factory as a service with the specified properties + * using the specified template argument as service interface type with the framework. + * + *

+ * This method is provided as a convenience when factory will only be registered under * a single class name whose type is available to the caller. It is otherwise identical to - * RegisterService(const char*, US_BASECLASS_NAME*, const ServiceProperties&) but should be preferred + * RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred * since it avoids errors in the string literal identifying the class name or interface identifier. * + * Example usage: + * \snippet uServices-registration/main.cpp 1-1 + * \snippet uServices-registration/main.cpp f1 + * * @tparam S The type under which the service can be located. - * @param service The service object or a ServiceFactory object. + * @param factory The ServiceFactory or PrototypeServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. - * @see RegisterService(const char*, us::Base*, const ServiceProperties&) + * @throws ServiceException If the service type \c S is invalid or the + * \c service factory object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ template - ServiceRegistration RegisterService(US_BASECLASS_NAME* service, const ServiceProperties& properties = ServiceProperties()) + ServiceRegistration RegisterService(ServiceFactory* factory, const ServiceProperties& properties = ServiceProperties()) { - const char* clazz = us_service_interface_iid(); - if (clazz == 0) - { - throw ServiceException(std::string("The interface class you are registering your service ") + - us_service_impl_name(service) + " against has no US_DECLARE_SERVICE_INTERFACE macro"); - } - return RegisterService(clazz, service, properties); + InterfaceMap servicePointers = MakeInterfaceMap(factory); + return RegisterService(servicePointers, properties); + } + + /** + * Registers the specified service factory as a service with the specified properties + * using the specified template argument as service interface type with the framework. + * + *

+ * This method is identical to the RegisterService(ServiceFactory*, const ServiceProperties&) + * method except that it supports two service interface types. + * + * Example usage: + * \snippet uServices-registration/main.cpp 2-1 + * \snippet uServices-registration/main.cpp f2 + * + * @tparam I1 The first interface type under which the service can be located. + * @tparam I2 The second interface type under which the service can be located. + * @param factory The ServiceFactory or PrototypeServiceFactory object. + * @param properties The properties for this service. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws ServiceException If the service type \c S is invalid or the + * \c service factory object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) + */ + template + ServiceRegistration RegisterService(ServiceFactory* factory, const ServiceProperties& properties = ServiceProperties()) + { + InterfaceMap servicePointers = MakeInterfaceMap(factory); + return RegisterService(servicePointers, properties); + } + + /** + * Registers the specified service factory as a service with the specified properties + * using the specified template argument as service interface type with the framework. + * + *

+ * This method is identical to the RegisterService(ServiceFactory*, const ServiceProperties&) + * method except that it supports three service interface types. + * + * @tparam I1 The first interface type under which the service can be located. + * @tparam I2 The second interface type under which the service can be located. + * @tparam I3 The third interface type under which the service can be located. + * @param factory The ServiceFactory or PrototypeServiceFactory object. + * @param properties The properties for this service. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws ServiceException If the service type \c S is invalid or the + * \c service factory object is NULL. + * + * @see RegisterService(const InterfaceMap&, const ServiceProperties&) + */ + template + ServiceRegistration RegisterService(ServiceFactory* factory, const ServiceProperties& properties = ServiceProperties()) + { + InterfaceMap servicePointers = MakeInterfaceMap(factory); + return RegisterService(servicePointers, properties); } /** * Returns a list of ServiceReference objects. The returned * list contains services that * were registered under the specified class and match the specified filter * expression. * *

* The list is valid at the time of the call to this method. However since * the Micro Services framework is a very dynamic environment, services can be modified or * unregistered at any time. * *

* The specified filter expression is used to select the * registered services whose service properties contain keys and values * which satisfy the filter expression. See LDAPFilter for a description * of the filter syntax. If the specified filter is * empty, all registered services are considered to match the * filter. If the specified filter expression cannot be parsed, * an std::invalid_argument will be thrown with a human readable * message where the filter became unparsable. * *

* The result is a list of ServiceReference objects for all * services that meet all of the following conditions: *

    *
  • If the specified class name, clazz, is not * empty, the service must have been registered with the * specified class name. The complete list of class names with which a * service was registered is available from the service's * {@link ServiceConstants#OBJECTCLASS() objectClass} property. *
  • If the specified filter is not empty, the * filter expression must match the service. *
* * @param clazz The class name with which the service was registered or * an empty string for all services. * @param filter The filter expression or empty for all * services. * @return A list of ServiceReference objects or * an empty list if no services are registered which satisfy the * search. * @throws std::invalid_argument If the specified filter * contains an invalid filter expression that cannot be parsed. * @throws std::logic_error If this ModuleContext is no longer valid. */ - std::list GetServiceReferences(const std::string& clazz, - const std::string& filter = std::string()); + std::vector GetServiceReferences(const std::string& clazz, const std::string& filter = std::string()); /** * Returns a list of ServiceReference objects. The returned * list contains services that * were registered under the interface id of the template argument S * and match the specified filter expression. * *

* This method is identical to GetServiceReferences(const std::string&, const std::string&) except that * the class name for the service object is automatically deduced from the template argument. * * @tparam S The type under which the requested service objects must have been registered. * @param filter The filter expression or empty for all * services. * @return A list of ServiceReference objects or * an empty list if no services are registered which satisfy the * search. * @throws std::invalid_argument If the specified filter * contains an invalid filter expression that cannot be parsed. * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws ServiceException If the service type \c S is invalid. + * * @see GetServiceReferences(const std::string&, const std::string&) */ template - std::list GetServiceReferences(const std::string& filter = std::string()) + std::vector > GetServiceReferences(const std::string& filter = std::string()) { - const char* clazz = us_service_interface_iid(); + const char* clazz = us_service_interface_iid(); if (clazz == 0) throw ServiceException("The service interface class has no US_DECLARE_SERVICE_INTERFACE macro"); - return GetServiceReferences(std::string(clazz), filter); + typedef std::vector BaseVectorT; + BaseVectorT serviceRefs = GetServiceReferences(std::string(clazz), filter); + std::vector > result; + for(BaseVectorT::const_iterator i = serviceRefs.begin(); i != serviceRefs.end(); ++i) + { + result.push_back(ServiceReference(*i)); + } + return result; } /** * Returns a ServiceReference object for a service that * implements and was registered under the specified class. * *

* The returned ServiceReference object is valid at the time of * the call to this method. However as the Micro Services framework is a very dynamic * environment, services can be modified or unregistered at any time. * *

* This method is the same as calling * {@link ModuleContext::GetServiceReferences(const std::string&, const std::string&)} with an * empty filter expression. It is provided as a convenience for * when the caller is interested in any service that implements the * specified class. *

* If multiple such services exist, the service with the highest ranking (as * specified in its ServiceConstants::SERVICE_RANKING() property) is returned. *

* If there is a tie in ranking, the service with the lowest service ID (as * specified in its ServiceConstants::SERVICE_ID() property); that is, the * service that was registered first is returned. * * @param clazz The class name with which the service was registered. * @return A ServiceReference object, or an invalid ServiceReference if * no services are registered which implement the named class. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If no service was registered under the given class name. + * * @see #GetServiceReferences(const std::string&, const std::string&) */ - ServiceReference GetServiceReference(const std::string& clazz); + ServiceReferenceU GetServiceReference(const std::string& clazz); /** * Returns a ServiceReference object for a service that * implements and was registered under the specified template class argument. * *

* This method is identical to GetServiceReference(const std::string&) except that * the class name for the service object is automatically deduced from the template argument. * * @tparam S The type under which the requested service must have been registered. * @return A ServiceReference object, or an invalid ServiceReference if * no services are registered which implement the type S. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException It no service was registered under the given class name. * @see #GetServiceReference(const std::string&) * @see #GetServiceReferences(const std::string&) */ template - ServiceReference GetServiceReference() + ServiceReference GetServiceReference() { - const char* clazz = us_service_interface_iid(); + const char* clazz = us_service_interface_iid(); if (clazz == 0) throw ServiceException("The service interface class has no US_DECLARE_SERVICE_INTERFACE macro"); - return GetServiceReference(std::string(clazz)); + return ServiceReference(GetServiceReference(std::string(clazz))); } /** * Returns the service object referenced by the specified - * ServiceReference object. + * ServiceReferenceBase object. *

* A module's use of a service is tracked by the module's use count of that * service. Each time a service's service object is returned by - * {@link #GetService(const ServiceReference&)} the context module's use count for + * {@link #GetService(const ServiceReference&)} the context module's use count for * that service is incremented by one. Each time the service is released by - * {@link #UngetService(const ServiceReference&)} the context module's use count + * {@link #UngetService(const ServiceReferenceBase&)} the context module's use count * for that service is decremented by one. *

* When a module's use count for a service drops to zero, the module should * no longer use that service. * *

* This method will always return 0 when the service * associated with this reference has been unregistered. * *

* The following steps are taken to get the service object: *

    *
  1. If the service has been unregistered, 0 is returned. *
  2. The context module's use count for this service is incremented by * one. *
  3. If the context module's use count for the service is currently one * and the service was registered with an object implementing the * ServiceFactory interface, the * {@link ServiceFactory::GetService} method is * called to create a service object for the context module. This service * object is cached by the framework. While the context module's use count * for the service is greater than zero, subsequent calls to get the * services's service object for the context module will return the cached * service object.
    * If the ServiceFactory object throws an * exception, 0 is returned and a warning is logged. *
  4. The service object for the service is returned. *
* * @param reference A reference to the service. * @return A service object for the service associated with * reference or 0 if the service is not * registered or the ServiceFactory threw * an exception. * @throws std::logic_error If this ModuleContext is no * longer valid. * @throws std::invalid_argument If the specified - * ServiceReference is invalid (default constructed). - * @see #UngetService(const ServiceReference&) + * ServiceReferenceBase is invalid (default constructed). + * @see #UngetService(const ServiceReferenceBase&) * @see ServiceFactory */ - US_BASECLASS_NAME* GetService(const ServiceReference& reference); + void* GetService(const ServiceReferenceBase& reference); + + InterfaceMap GetService(const ServiceReferenceU& reference); /** * Returns the service object referenced by the specified * ServiceReference object. *

- * This is a convenience method which is identical to US_BASECLASS_NAME* GetService(const ServiceReference&) + * This is a convenience method which is identical to void* GetService(const ServiceReferenceBase&) * except that it casts the service object to the supplied template argument type * * @tparam S The type the service object will be cast to. * @return A service object for the service associated with * reference or 0 if the service is not * registered, the ServiceFactory threw * an exception or the service could not be casted to the desired type. * @throws std::logic_error If this ModuleContext is no * longer valid. * @throws std::invalid_argument If the specified * ServiceReference is invalid (default constructed). - * @see #GetService(const ServiceReference&) - * @see #UngetService(const ServiceReference&) + * @see #GetService(const ServiceReferenceBase&) + * @see #UngetService(const ServiceReferenceBase&) * @see ServiceFactory */ template - S* GetService(const ServiceReference& reference) + S* GetService(const ServiceReference& reference) + { + const ServiceReferenceBase& baseRef = reference; + return reinterpret_cast(GetService(baseRef)); + } + + /** + * Returns the ServiceObjects object for the service referenced by the specified + * ServiceReference object. The ServiceObjects object can be used to obtain + * multiple service objects for services with prototype scope. For services with + * singleton or module scope, the ServiceObjects::GetService() method behaves + * the same as the GetService(const ServiceReference&) method and the + * ServiceObjects::UngetService(const ServiceReferenceBase&) method behaves the + * same as the UngetService(const ServiceReferenceBase&) method. That is, only one, + * use-counted service object is available from the ServiceObjects object. + * + * @tparam S Type of Service. + * @param reference A reference to the service. + * @return A ServiceObjects object for the service associated with the specified + * reference or an invalid instance if the service is not registered. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws std::invalid_argument If the specified ServiceReference is invalid + * (default constructed or the service has been unregistered) + * + * @see PrototypeServiceFactory + */ + template + ServiceObjects GetServiceObjects(const ServiceReference& reference) { - return dynamic_cast(GetService(reference)); + return ServiceObjects(this, reference); } /** * Releases the service object referenced by the specified * ServiceReference object. If the context module's use count * for the service is zero, this method returns false. * Otherwise, the context modules's use count for the service is decremented * by one. * *

* The service's service object should no longer be used and all references * to it should be destroyed when a module's use count for the service drops * to zero. * *

* The following steps are taken to unget the service object: *

    *
  1. If the context module's use count for the service is zero or the * service has been unregistered, false is returned. *
  2. The context module's use count for this service is decremented by * one. *
  3. If the context module's use count for the service is currently zero * and the service was registered with a ServiceFactory object, * the ServiceFactory#UngetService * method is called to release the service object for the context module. *
  4. true is returned. *
* * @param reference A reference to the service to be released. * @return false if the context module's use count for the * service is zero or if the service has been unregistered; * true otherwise. * @throws std::logic_error If this ModuleContext is no * longer valid. * @see #GetService * @see ServiceFactory */ - bool UngetService(const ServiceReference& reference); + bool UngetService(const ServiceReferenceBase& reference); void AddServiceListener(const ServiceListener& delegate, const std::string& filter = std::string()); void RemoveServiceListener(const ServiceListener& delegate); void AddModuleListener(const ModuleListener& delegate); void RemoveModuleListener(const ModuleListener& delegate); /** * Adds the specified callback with the * specified filter to the context modules's list of listeners. * See LDAPFilter for a description of the filter syntax. Listeners * are notified when a service has a lifecycle state change. * *

* You must take care to remove registered listeners befor the receiver * object is destroyed. However, the Micro Services framework takes care * of removing all listeners registered by this context module's classes * after the module is unloaded. * *

* If the context module's list of listeners already contains a pair (r,c) * of receiver and callback such that * (r == receiver && c == callback), then this * method replaces that callback's filter (which may be empty) * with the specified one (which may be empty). * *

* The callback is called if the filter criteria is met. To filter based * upon the class of the service, the filter should reference the * ServiceConstants#OBJECTCLASS() property. If filter is * empty, all services are considered to match the filter. * *

* When using a filter, it is possible that the * ServiceEvents for the complete lifecycle of a service * will not be delivered to the callback. For example, if the * filter only matches when the property x has * the value 1, the callback will not be called if the * service is registered with the property x not set to the * value 1. Subsequently, when the service is modified * setting property x to the value 1, the * filter will match and the callback will be called with a * ServiceEvent of type MODIFIED. Thus, the * callback will not be called with a ServiceEvent of type * REGISTERED. * * @tparam R The type of the receiver (containing the member function to be called) * @param receiver The object to connect to. * @param callback The member function pointer to call. * @param filter The filter criteria. * @throws std::invalid_argument If filter contains an * invalid filter string that cannot be parsed. * @throws std::logic_error If this ModuleContext is no * longer valid. * @see ServiceEvent * @see RemoveServiceListener() */ template void AddServiceListener(R* receiver, void(R::*callback)(const ServiceEvent), const std::string& filter = std::string()) { AddServiceListener(ServiceListenerMemberFunctor(receiver, callback), static_cast(receiver), filter); } /** * Removes the specified callback from the context module's * list of listeners. * *

* If the (receiver,callback) pair is not contained in this * context module's list of listeners, this method does nothing. * * @tparam R The type of the receiver (containing the member function to be removed) * @param receiver The object from which to disconnect. * @param callback The member function pointer to remove. * @throws std::logic_error If this ModuleContext is no * longer valid. * @see AddServiceListener() */ template void RemoveServiceListener(R* receiver, void(R::*callback)(const ServiceEvent)) { RemoveServiceListener(ServiceListenerMemberFunctor(receiver, callback), static_cast(receiver)); } /** * Adds the specified callback to the context modules's list * of listeners. Listeners are notified when a module has a lifecycle * state change. * *

* If the context module's list of listeners already contains a pair (r,c) * of receiver and callback such that * (r == receiver && c == callback), then this method does nothing. * * @tparam R The type of the receiver (containing the member function to be called) * @param receiver The object to connect to. * @param callback The member function pointer to call. * @throws std::logic_error If this ModuleContext is no * longer valid. * @see ModuleEvent */ template void AddModuleListener(R* receiver, void(R::*callback)(const ModuleEvent)) { AddModuleListener(ModuleListenerMemberFunctor(receiver, callback), static_cast(receiver)); } /** * Removes the specified callback from the context module's * list of listeners. * *

* If the (receiver,callback) pair is not contained in this * context module's list of listeners, this method does nothing. * * @tparam R The type of the receiver (containing the member function to be removed) * @param receiver The object from which to disconnect. * @param callback The member function pointer to remove. * @throws std::logic_error If this ModuleContext is no * longer valid. * @see AddModuleListener() */ template void RemoveModuleListener(R* receiver, void(R::*callback)(const ModuleEvent)) { RemoveModuleListener(ModuleListenerMemberFunctor(receiver, callback), static_cast(receiver)); } private: friend class Module; friend class ModulePrivate; ModuleContext(ModulePrivate* module); // purposely not implemented ModuleContext(const ModuleContext&); ModuleContext& operator=(const ModuleContext&); void AddServiceListener(const ServiceListener& delegate, void* data, const std::string& filter); void RemoveServiceListener(const ServiceListener& delegate, void* data); void AddModuleListener(const ModuleListener& delegate, void* data); void RemoveModuleListener(const ModuleListener& delegate, void* data); ModuleContextPrivate * const d; }; US_END_NAMESPACE #endif /* USMODULECONTEXT_H_ */ diff --git a/Core/Code/CppMicroServices/src/module/usModuleEvent.cpp b/Core/CppMicroServices/src/module/usModuleEvent.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleEvent.cpp rename to Core/CppMicroServices/src/module/usModuleEvent.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleEvent.h b/Core/CppMicroServices/src/module/usModuleEvent.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleEvent.h rename to Core/CppMicroServices/src/module/usModuleEvent.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleImport.h b/Core/CppMicroServices/src/module/usModuleImport.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleImport.h rename to Core/CppMicroServices/src/module/usModuleImport.h diff --git a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp b/Core/CppMicroServices/src/module/usModuleInfo.cpp similarity index 83% copy from Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp copy to Core/CppMicroServices/src/module/usModuleInfo.cpp index 1c0ca73f54..804c133c8a 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp +++ b/Core/CppMicroServices/src/module/usModuleInfo.cpp @@ -1,31 +1,34 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#include + +#include "usModuleInfo.h" US_BEGIN_NAMESPACE -struct US_ABI_EXPORT TestModuleAL_1_Dummy -{ -}; +ModuleInfo::ModuleInfo(const std::string& name, const std::string& libName) + : name(name) + , libName(libName) + , id(0) + , activatorHook(NULL) +{} US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/module/usModuleInfo.h b/Core/CppMicroServices/src/module/usModuleInfo.h similarity index 92% rename from Core/Code/CppMicroServices/src/module/usModuleInfo.h rename to Core/CppMicroServices/src/module/usModuleInfo.h index da9da07803..6d73321982 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleInfo.h +++ b/Core/CppMicroServices/src/module/usModuleInfo.h @@ -1,80 +1,77 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEINFO_H #define USMODULEINFO_H #include #include #include #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4251) #endif US_BEGIN_NAMESPACE struct ModuleActivator; /** * This class is not intended to be used directly. It is exported to support * the CppMicroServices module system. */ struct US_EXPORT ModuleInfo { - ModuleInfo(const std::string& name, const std::string& libName, const std::string& autoLoadDir, - const std::string& moduleDeps, const std::string& version); + ModuleInfo(const std::string& name, const std::string& libName); typedef ModuleActivator*(*ModuleActivatorHook)(void); typedef int(*InitResourcesHook)(ModuleInfo*); typedef const unsigned char* ModuleResourceData; std::string name; std::string libName; - std::string moduleDeps; - std::string version; std::string location; std::string autoLoadDir; long id; ModuleActivatorHook activatorHook; // In case of statically linked (imported) modules, there could // be more than one set of ModuleResourceData pointers. We aggregate // all pointers here. std::vector resourceData; std::vector resourceNames; std::vector resourceTree; }; US_END_NAMESPACE #ifdef _MSC_VER # pragma warning(pop) #endif #endif // USMODULEINFO_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleInitialization.h b/Core/CppMicroServices/src/module/usModuleInitialization.h similarity index 74% rename from Core/Code/CppMicroServices/src/module/usModuleInitialization.h rename to Core/CppMicroServices/src/module/usModuleInitialization.h index 96b9a60b8f..b0df114839 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleInitialization.h +++ b/Core/CppMicroServices/src/module/usModuleInitialization.h @@ -1,170 +1,170 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include #ifndef USMODULEINITIALIZATION_H #define USMODULEINITIALIZATION_H /** * \ingroup MicroServices * * \brief Creates initialization code for a module. * * Each module which wants to register itself with the CppMicroServices library - * has to put a call to this macro (or to #US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR) - * in one of its source files. + * has to put a call to this macro in one of its source files. * - * Example call for a module with file-name "libmylibname.so". + * Example call for a module with file-name "libmylibname.so": * \code - * US_INITIALIZE_MODULE("My Service Implementation", "mylibname", "", "1.0.0") + * US_INITIALIZE_MODULE("My Service Implementation", "mylibname") * \endcode * * This will initialize the module for use with the CppMicroServices library, using a default * auto-load directory named after the provided library name in \c _module_libname. * - * \sa US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR + * \sa MicroServices_AutoLoading * * \remarks If you are using CMake, consider using the provided CMake macro * usFunctionGenerateModuleInit(). * * \param _module_name A human-readable name for the module. * If you use this macro in a source file for an executable, the module name must * be a valid C-identifier (no spaces etc.). * \param _module_libname The physical name of the module, withou prefix or suffix. - * \param _module_depends A list of module dependencies. This is meta-data only. - * \param _module_version A version string in the form of "...". - * - * \note If you use this macro in a source file compiled into an executable, additional - * requirements for the macro arguments apply: - * - The \c _module_name argument must be a valid C-identifier (no spaces etc.). - * - The \c _module_libname argument must be an empty string. * + * \note If you want to create initialization code for an executable, see + * #US_INITIALIZE_EXECUTABLE. */ -#define US_INITIALIZE_MODULE(_module_name, _module_libname, _module_depends, _module_version) \ - US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR(_module_name, _module_libname, _module_libname, _module_depends, _module_version) - -/** - * \ingroup MicroServices - * - * \brief Creates initialization code for a module using a custom auto-load directory. - * - * Each module which wants to register itself with the CppMicroServices library - * has to put a call to this macro (or to #US_INITIALIZE_MODULE) in one of its source files. - * - * Example call for a module with file-name "libmylibname.so". - * \code - * US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR("My Service Implementation", "mylibname", "autoload_mysublibs", "", "1.0.0") - * \endcode - * - * \remarks If you are using CMake, consider using the provided CMake macro - * usFunctionGenerateModuleInit(). - * - * \param _module_name A human-readable name for the module. - * If you use this macro in a source file for an executable, the module name must - * be a valid C-identifier (no spaces etc.). - * \param _module_libname The physical name of the module, withou prefix or suffix. - * \param _module_autoload_dir A directory name relative to this modules library location from which - * modules will be auto-loaded during activation of this module. Provide an empty string to - * disable auto-loading for this module. - * \param _module_depends A list of module dependencies. This is meta-data only. - * \param _module_version A version string in the form of "...". - */ -#define US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR(_module_name, _module_libname, _module_autoload_dir, _module_depends, _module_version) \ +#define US_INITIALIZE_MODULE(_module_name, _module_libname) \ US_BEGIN_NAMESPACE \ \ /* Declare a file scoped ModuleInfo object */ \ -US_GLOBAL_STATIC_WITH_ARGS(ModuleInfo, moduleInfo, (_module_name, _module_libname, _module_autoload_dir, _module_depends, _module_version)) \ +US_GLOBAL_STATIC_WITH_ARGS(ModuleInfo, moduleInfo, (_module_name, _module_libname)) \ \ /* This class is used to statically initialize the library within the C++ Micro services \ library. It looks up a library specific C-style function returning an instance \ of the ModuleActivator interface. */ \ class US_ABI_LOCAL ModuleInitializer { \ \ public: \ \ ModuleInitializer() \ { \ + ModuleInfo*(*moduleInfoPtr)() = moduleInfo; \ std::string location = ModuleUtils::GetLibraryPath(moduleInfo()->libName, \ - reinterpret_cast(moduleInfo)); \ + *reinterpret_cast(&moduleInfoPtr)); \ std::string activator_func = "_us_module_activator_instance_"; \ if(moduleInfo()->libName.empty()) \ { \ activator_func.append(moduleInfo()->name); \ } \ else \ { \ activator_func.append(moduleInfo()->libName); \ } \ \ moduleInfo()->location = location; \ \ if (moduleInfo()->libName.empty()) \ { \ /* make sure we retrieve symbols from the executable, if "libName" is empty */ \ location.clear(); \ } \ - moduleInfo()->activatorHook = reinterpret_cast(ModuleUtils::GetSymbol(location, activator_func.c_str())); \ + *reinterpret_cast(&moduleInfo()->activatorHook) = ModuleUtils::GetSymbol(location, activator_func.c_str()); \ \ Register(); \ } \ \ static void Register() \ { \ ModuleRegistry::Register(moduleInfo()); \ } \ \ ~ModuleInitializer() \ { \ ModuleRegistry::UnRegister(moduleInfo()); \ } \ \ }; \ \ US_ABI_LOCAL ModuleContext* GetModuleContext() \ { \ /* make sure the module is registered */ \ if (moduleInfo()->id == 0) \ { \ ModuleInitializer::Register(); \ } \ \ return ModuleRegistry::GetModule(moduleInfo()->id)->GetModuleContext(); \ } \ \ US_END_NAMESPACE \ \ static US_PREPEND_NAMESPACE(ModuleInitializer) _InitializeModule; +/** + * \ingroup MicroServices + * + * \brief Creates initialization code for an executable. + * + * Each executable which wants to register itself with the CppMicroServices library + * has to put a call to this macro in one of its source files. This ensures that the + * executable will get its own ModuleContext instance and can access the service registry. + * + * Example call for an executable: + * \code + * US_INITIALIZE_EXECUTABLE("my_executable") + * \endcode + * + * This will initialize the executable for use with the CppMicroServices library, using a default + * auto-load directory named after the provided executable id in \c _executable_id. + * + * \sa MicroServices_AutoLoading + * + * \remarks If you are using CMake, consider using the provided CMake macro + * usFunctionGenerateExecutableInit(). + * + * \param _executable_id A valid C identifier for the executable (no spaces etc.). + */ +#define US_INITIALIZE_EXECUTABLE(_executable_id) \ + US_INITIALIZE_MODULE(_executable_id, "") + +// If the CppMicroServices library was statically build, executables will share the +// initialization code with the CppMicroServices library. +#ifndef US_BUILD_SHARED_LIBS +#undef US_INITIALIZE_EXECUTABLE +#define US_INITIALIZE_EXECUTABLE(_a) +#endif + // Static modules usually don't get initialization code. They are initialized within the // module importing the static module(s). #if defined(US_STATIC_MODULE) && !defined(US_FORCE_MODULE_INIT) -#undef US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR -#define US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR(_a,_b,_c,_d,_e) +#undef US_INITIALIZE_MODULE +#define US_INITIALIZE_MODULE(_a,_b) #endif #endif // USMODULEINITIALIZATION_H diff --git a/Core/CppMicroServices/src/module/usModuleManifest.cpp b/Core/CppMicroServices/src/module/usModuleManifest.cpp new file mode 100644 index 0000000000..7a2dde83c2 --- /dev/null +++ b/Core/CppMicroServices/src/module/usModuleManifest.cpp @@ -0,0 +1,142 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usModuleManifest_p.h" + +#include + +US_BEGIN_NAMESPACE + +ModuleManifest::ModuleManifest() +{ +} + +void ModuleManifest::Parse(std::istream& is) +{ + Json::Value root; + Json::Reader jsonReader(Json::Features::strictMode()); + if (!jsonReader.parse(is, root, false)) + { + throw std::runtime_error(jsonReader.getFormattedErrorMessages()); + } + + if (!root.isObject()) + { + throw std::runtime_error("The Json root element must be an object."); + } + + ParseJsonObject(root, m_Properties); +} + +Any ModuleManifest::ParseJsonValue(const Json::Value& jsonValue) +{ + if (jsonValue.isObject()) + { + Any any = AnyMap(); + ParseJsonObject(jsonValue, ref_any_cast(any)); + return any; + } + else if (jsonValue.isArray()) + { + Any any = AnyVector(); + ParseJsonArray(jsonValue, ref_any_cast(any)); + return any; + } + else if (jsonValue.isString()) + { + return Any(jsonValue.asString()); + } + else if (jsonValue.isBool()) + { + return Any(jsonValue.asBool()); + } + else if (jsonValue.isDouble()) + { + return Any(jsonValue.asDouble()); + } + else if (jsonValue.isIntegral()) + { + return Any(jsonValue.asInt()); + } + + return Any(); +} + +void ModuleManifest::ParseJsonObject(const Json::Value& jsonObject, std::map& anyMap) +{ + for (Json::Value::const_iterator it = jsonObject.begin(); + it != jsonObject.end(); ++it) + { + const Json::Value& jsonValue = *it; + Any anyValue = ParseJsonValue(jsonValue); + if (!anyValue.Empty()) + { + anyMap.insert(std::make_pair(it.memberName(), anyValue)); + } + } +} + +void ModuleManifest::ParseJsonArray(const Json::Value& jsonArray, ModuleManifest::AnyVector& anyVector) +{ + for (Json::Value::const_iterator it = jsonArray.begin(); + it != jsonArray.end(); ++it) + { + const Json::Value& jsonValue = *it; + Any anyValue = ParseJsonValue(jsonValue); + if (!anyValue.Empty()) + { + anyVector.push_back(anyValue); + } + } +} + +bool ModuleManifest::Contains(const std::string& key) const +{ + return m_Properties.count(key) > 0; +} + +Any ModuleManifest::GetValue(const std::string& key) const +{ + AnyMap::const_iterator iter = m_Properties.find(key); + if (iter != m_Properties.end()) + { + return iter->second; + } + return Any(); +} + +std::vector ModuleManifest::GetKeys() const +{ + std::vector keys; + for (AnyMap::const_iterator iter = m_Properties.begin(); + iter != m_Properties.end(); ++iter) + { + keys.push_back(iter->first); + } + return keys; +} + +void ModuleManifest::SetValue(const std::string& key, const Any& value) +{ + m_Properties[key] = value; +} + +US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h b/Core/CppMicroServices/src/module/usModuleManifest_p.h similarity index 56% rename from Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h rename to Core/CppMicroServices/src/module/usModuleManifest_p.h index 80b1faa73b..670094b070 100644 --- a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h +++ b/Core/CppMicroServices/src/module/usModuleManifest_p.h @@ -1,68 +1,62 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#ifndef USTESTUTILSHAREDLIBRARY_H -#define USTESTUTILSHAREDLIBRARY_H +#ifndef USMODULEMANIFEST_P_H +#define USMODULEMANIFEST_P_H -#include "usConfig.h" +#include "usAny.h" -#include +#include "json_p.h" US_BEGIN_NAMESPACE -class SharedLibraryHandle +class ModuleManifest { public: - SharedLibraryHandle(); + ModuleManifest(); - SharedLibraryHandle(const std::string& name); + void Parse(std::istream& is); - virtual ~SharedLibraryHandle(); + bool Contains(const std::string& key) const; - void Load(); + Any GetValue(const std::string& key) const; - void Load(const std::string& name); + std::vector GetKeys() const; - void Unload(); + void SetValue(const std::string& key, const Any& value); - std::string GetAbsolutePath(const std::string& name); - - std::string GetAbsolutePath(); - - static std::string GetLibraryPath(); - - static std::string Suffix(); +private: - static std::string Prefix(); + typedef std::map AnyMap; + typedef std::vector AnyVector; -private: + Any ParseJsonValue(const Json::Value& jsonValue); - SharedLibraryHandle(const SharedLibraryHandle&); - SharedLibraryHandle& operator = (const SharedLibraryHandle&); + void ParseJsonObject(const Json::Value& jsonObject, AnyMap& anyMap); + void ParseJsonArray(const Json::Value& jsonArray, AnyVector& anyVector); - std::string m_Name; - void* m_Handle; + AnyMap m_Properties; }; US_END_NAMESPACE -#endif // USTESTUTILSHAREDLIBRARY_H +#endif // USMODULEMANIFEST_P_H diff --git a/Core/Code/CppMicroServices/src/module/usModulePrivate.cpp b/Core/CppMicroServices/src/module/usModulePrivate.cpp similarity index 70% rename from Core/Code/CppMicroServices/src/module/usModulePrivate.cpp rename to Core/CppMicroServices/src/module/usModulePrivate.cpp index 77e10d4464..6c99393e4a 100644 --- a/Core/Code/CppMicroServices/src/module/usModulePrivate.cpp +++ b/Core/CppMicroServices/src/module/usModulePrivate.cpp @@ -1,248 +1,267 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include "usModulePrivate.h" #include "usModule.h" #include "usModuleActivator.h" #include "usModuleUtils_p.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" #include "usCoreModuleContext_p.h" #include "usServiceRegistration.h" -#include "usServiceReferencePrivate.h" +#include "usServiceReferenceBasePrivate.h" #include #include #include US_BEGIN_NAMESPACE AtomicInt ModulePrivate::idCounter; ModulePrivate::ModulePrivate(Module* qq, CoreModuleContext* coreCtx, ModuleInfo* info) : coreCtx(coreCtx) , info(*info) , moduleContext(0) , moduleActivator(0) , q(qq) { // Parse the statically imported module library names typedef const char*(*GetImportedModulesFunc)(void); std::string getImportedModulesSymbol("_us_get_imported_modules_for_"); getImportedModulesSymbol += this->info.libName; std::string location = this->info.location; if (this->info.libName.empty()) { /* make sure we retrieve symbols from the executable, if "libName" is empty */ location.clear(); } GetImportedModulesFunc getImportedModulesFunc = reinterpret_cast( ModuleUtils::GetSymbol(location, getImportedModulesSymbol.c_str())); if (getImportedModulesFunc != NULL) { std::string importedStaticModuleLibNames = getImportedModulesFunc(); std::istringstream iss(importedStaticModuleLibNames); std::copy(std::istream_iterator(iss), std::istream_iterator(), std::back_inserter >(this->staticModuleLibNames)); } InitializeResources(location); - std::stringstream propId; - propId << this->info.id; - properties[Module::PROP_ID()] = propId.str(); - - std::stringstream propModuleDepends; - std::stringstream propLibDepends; - - int counter = 0; - int counter2 = 0; - std::stringstream ss(this->info.moduleDeps); - while (ss) + // Check if the module provides a manifest.json file and if yes, parse it. + ModuleResource manifestRes; + std::map::iterator resourceTreeIter = mapLibNameToResourceTrees.find(this->info.libName); + if (resourceTreeIter != mapLibNameToResourceTrees.end() && resourceTreeIter->second->IsValid()) { - std::string moduleDep; - ss >> moduleDep; - if (!moduleDep.empty()) + manifestRes = ModuleResource("/manifest.json", resourceTreeIter->second, resourceTreePtrs); + if (manifestRes) { - Module* dep = ModuleRegistry::GetModule(moduleDep); - if (dep) + ModuleResourceStream manifestStream(manifestRes); + try { - requiresIds.push_back(dep->GetModuleId()); - if (counter > 0) propModuleDepends << ", "; - propModuleDepends << moduleDep; - ++counter; + moduleManifest.Parse(manifestStream); } - else + catch (const std::exception& e) { - requiresLibs.push_back(moduleDep); - if (counter2 > 0) propLibDepends << ", "; - propLibDepends << moduleDep; - ++counter2; + US_ERROR << "Parsing of manifest.json for module " << info->location << " failed: " << e.what(); } } } - properties[Module::PROP_MODULE_DEPENDS()] = propModuleDepends.str(); - properties[Module::PROP_LIB_DEPENDS()] = propLibDepends.str(); - - if (!this->info.version.empty()) + // Check if we got version information and validate the version identifier + if (moduleManifest.Contains(Module::PROP_VERSION())) { + Any versionAny = moduleManifest.GetValue(Module::PROP_VERSION()); + std::string errMsg; + if (versionAny.Type() != typeid(std::string)) + { + errMsg = std::string("The version identifier must be a string"); + } try { - version = ModuleVersion(this->info.version); - properties[Module::PROP_VERSION()] = this->info.version; + version = ModuleVersion(versionAny.ToString()); } catch (const std::exception& e) { - throw std::invalid_argument(std::string("CppMicroServices module does not specify a valid version identifier. Got exception: ") + e.what()); + errMsg = std::string("The version identifier is invalid: ") + e.what(); + } + + if (!errMsg.empty()) + { + throw std::invalid_argument(std::string("The Json value for ") + Module::PROP_VERSION() + " for module " + + info->location + " is not valid: " + errMsg); } } - properties[Module::PROP_LOCATION()] = this->info.location; - properties[Module::PROP_NAME()] = this->info.name; + std::stringstream propId; + propId << this->info.id; + moduleManifest.SetValue(Module::PROP_ID(), propId.str()); + moduleManifest.SetValue(Module::PROP_LOCATION(), this->info.location); + moduleManifest.SetValue(Module::PROP_NAME(), this->info.name); + + if (moduleManifest.Contains(Module::PROP_AUTOLOAD_DIR())) + { + this->info.autoLoadDir = moduleManifest.GetValue(Module::PROP_AUTOLOAD_DIR()).ToString(); + } + else + { + // default to the library name or a special name for executables + if (!this->info.libName.empty()) + { + this->info.autoLoadDir = this->info.libName; + moduleManifest.SetValue(Module::PROP_AUTOLOAD_DIR(), Any(this->info.autoLoadDir)); + } + else + { + this->info.autoLoadDir = "main"; + moduleManifest.SetValue(Module::PROP_AUTOLOAD_DIR(), Any(this->info.autoLoadDir)); + } + } } ModulePrivate::~ModulePrivate() { delete moduleContext; for (std::size_t i = 0; i < this->resourceTreePtrs.size(); ++i) { delete resourceTreePtrs[i]; } } void ModulePrivate::RemoveModuleResources() { coreCtx->listeners.RemoveAllListeners(moduleContext); - std::list srs; + std::vector srs; coreCtx->services.GetRegisteredByModule(this, srs); - for (std::list::iterator i = srs.begin(); + for (std::vector::iterator i = srs.begin(); i != srs.end(); ++i) { try { i->Unregister(); } catch (const std::logic_error& /*ignore*/) { // Someone has unregistered the service after stop completed. // This should not occur, but we don't want get stuck in // an illegal state so we catch it. } } srs.clear(); coreCtx->services.GetUsedByModule(q, srs); - for (std::list::const_iterator i = srs.begin(); + for (std::vector::const_iterator i = srs.begin(); i != srs.end(); ++i) { - i->GetReference().d->UngetService(q, false); + i->GetReference(std::string()).d->UngetService(q, false); } for (std::size_t i = 0; i < resourceTreePtrs.size(); ++i) { resourceTreePtrs[i]->Invalidate(); } } void ModulePrivate::StartStaticModules() { std::string location = this->info.location; if (this->info.libName.empty()) { /* make sure we retrieve symbols from the executable, if "libName" is empty */ location.clear(); } for (std::vector::iterator i = staticModuleLibNames.begin(); i != staticModuleLibNames.end(); ++i) { std::string staticActivatorSymbol = "_us_module_activator_instance_"; staticActivatorSymbol += *i; ModuleInfo::ModuleActivatorHook staticActivator = reinterpret_cast(ModuleUtils::GetSymbol(location, staticActivatorSymbol.c_str())); if (staticActivator) { US_DEBUG << "Loading static activator " << *i; staticActivators.push_back(staticActivator); staticActivator()->Load(moduleContext); } else { US_DEBUG << "Could not find an activator for the static module " << (*i) << ". It propably does not provide an activator on purpose.\n Or you either " "forgot a US_IMPORT_MODULE macro call in " << info.libName << " or to link " << (*i) << " to " << info.libName << "."; } } } void ModulePrivate::StopStaticModules() { for (std::list::iterator i = staticActivators.begin(); i != staticActivators.end(); ++i) { (*i)()->Unload(moduleContext); } } void ModulePrivate::InitializeResources(const std::string& location) { // Get the resource data from static modules and this module std::vector moduleLibNames; moduleLibNames.push_back(this->info.libName); moduleLibNames.insert(moduleLibNames.end(), this->staticModuleLibNames.begin(), this->staticModuleLibNames.end()); std::string initResourcesSymbolPrefix = "_us_init_resources_"; for (std::size_t i = 0; i < moduleLibNames.size(); ++i) { std::string initResourcesSymbol = initResourcesSymbolPrefix + moduleLibNames[i]; ModuleInfo::InitResourcesHook initResourcesFunc = reinterpret_cast( ModuleUtils::GetSymbol(location, initResourcesSymbol.c_str())); if (initResourcesFunc) { initResourcesFunc(&this->info); } } // Initialize this modules resource trees assert(this->info.resourceData.size() == this->info.resourceNames.size()); assert(this->info.resourceNames.size() == this->info.resourceTree.size()); for (std::size_t i = 0; i < this->info.resourceData.size(); ++i) { resourceTreePtrs.push_back(new ModuleResourceTree(this->info.resourceTree[i], this->info.resourceNames[i], this->info.resourceData[i])); + mapLibNameToResourceTrees[moduleLibNames[i]] = resourceTreePtrs.back(); } } US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/module/usModulePrivate.h b/Core/CppMicroServices/src/module/usModulePrivate.h similarity index 94% rename from Core/Code/CppMicroServices/src/module/usModulePrivate.h rename to Core/CppMicroServices/src/module/usModulePrivate.h index 6d1f4e4a07..62af04b714 100644 --- a/Core/Code/CppMicroServices/src/module/usModulePrivate.h +++ b/Core/CppMicroServices/src/module/usModulePrivate.h @@ -1,105 +1,103 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULEPRIVATE_H #define USMODULEPRIVATE_H #include #include #include "usModuleRegistry.h" #include "usModuleVersion.h" #include "usModuleInfo.h" +#include "usModuleManifest_p.h" #include "usModuleResourceTree_p.h" #include "usAtomicInt_p.h" US_BEGIN_NAMESPACE class CoreModuleContext; class ModuleContext; struct ModuleActivator; /** * \ingroup MicroServices */ class ModulePrivate { public: /** * Construct a new module based on a ModuleInfo object. */ ModulePrivate(Module* qq, CoreModuleContext* coreCtx, ModuleInfo* info); virtual ~ModulePrivate(); void RemoveModuleResources(); void StartStaticModules(); void StopStaticModules(); CoreModuleContext* const coreCtx; - std::vector requiresIds; - - std::vector requiresLibs; - std::vector staticModuleLibNames; /** * Module version */ ModuleVersion version; ModuleInfo info; std::vector resourceTreePtrs; + std::map mapLibNameToResourceTrees; /** * ModuleContext for the module */ ModuleContext* moduleContext; ModuleActivator* moduleActivator; - std::map properties; + ModuleManifest moduleManifest; Module* const q; private: void InitializeResources(const std::string& location); std::list staticActivators; static AtomicInt idCounter; // purposely not implemented ModulePrivate(const ModulePrivate&); ModulePrivate& operator=(const ModulePrivate&); }; US_END_NAMESPACE #endif // USMODULEPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp b/Core/CppMicroServices/src/module/usModuleRegistry.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp rename to Core/CppMicroServices/src/module/usModuleRegistry.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleRegistry.h b/Core/CppMicroServices/src/module/usModuleRegistry.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleRegistry.h rename to Core/CppMicroServices/src/module/usModuleRegistry.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleResource.cpp b/Core/CppMicroServices/src/module/usModuleResource.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResource.cpp rename to Core/CppMicroServices/src/module/usModuleResource.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResource.h b/Core/CppMicroServices/src/module/usModuleResource.h similarity index 98% rename from Core/Code/CppMicroServices/src/module/usModuleResource.h rename to Core/CppMicroServices/src/module/usModuleResource.h index 9c6f4e9ec9..abfe1370a7 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleResource.h +++ b/Core/CppMicroServices/src/module/usModuleResource.h @@ -1,304 +1,305 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USMODULERESOURCE_H #define USMODULERESOURCE_H #include #include #include US_MSVC_PUSH_DISABLE_WARNING(4396) US_BEGIN_NAMESPACE class ModuleResourcePrivate; class ModuleResourceTree; /** * \ingroup MicroServices * * Represents a resource (text file, image, etc.) embedded in a CppMicroServices module. * * A \c %ModuleResource object provides information about a resource (external file) which * was embedded into this module's shared library. \c %ModuleResource objects can be obtained * be calling Module#GetResource or Module#FindResources. * * Example code for retreiving a resource object and reading its contents: * \snippet uServices-resources/main.cpp 1 * * %ModuleResource objects have value semantics and copies are very inexpensive. * * \see ModuleResourceStream * \see \ref MicroServices_Resources */ class US_EXPORT ModuleResource { public: /** * Creates in invalid %ModuleResource object. */ ModuleResource(); /** * Copy constructor. * @param resource The object to be copied. */ ModuleResource(const ModuleResource& resource); ~ModuleResource(); /** * Assignment operator. * * @param resource The %ModuleResource object which is assigned to this instance. * @return A reference to this %ModuleResource instance. */ ModuleResource& operator=(const ModuleResource& resource); /** * A less then operator using the full resource path as returned by * GetResourcePath() to define the ordering. * * @param resource The object to which this %ModuleResource object is compared to. * @return \c true if this %ModuleResource object is less then \c resource, * \c false otherwise. */ bool operator<(const ModuleResource& resource) const; /** * Equality operator for %ModuleResource objects. * * @param resource The object for testing equality. * @return \c true if this %ModuleResource object is equal to \c resource, i.e. * they are coming from the same module (shared or static) and have an equal * resource path, \c false otherwise. */ bool operator==(const ModuleResource& resource) const; /** * Inequality operator for %ModuleResource objects. * * @param resource The object for testing inequality. * @return The result of !(*this == resource). */ bool operator!=(const ModuleResource& resource) const; /** * Tests this %ModuleResource object for validity. * * Invalid %ModuleResource objects are created by the default constructor or * can be returned by the Module class if the resource path is not found. If a * module from which %ModuleResource objects have been obtained is un-loaded, * these objects become invalid. * * @return \c true if this %ModuleReource object is valid and can safely be used, * \c false otherwise. */ bool IsValid() const; /** * Returns \c true if the resource represents a file and the resource data * is in a compressed format, \c false otherwise. * * @return \c true if the resource data is compressed, \c false otherwise. */ bool IsCompressed() const; /** * Boolean conversion operator using IsValid(). */ operator bool() const; /** * Returns the name of the resource, excluding the path. * * Example: * \code * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); * std::string name = resource.GetName(); // name = "archive.tar.gz" * \endcode * * @return The resource name. * @see GetPath(), GetResourcePath() */ std::string GetName() const; /** * Returns the resource's path, without the file name. * * Example: * \code * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); * std::string path = resource.GetPath(); // path = "/data" * \endcode * * @return The resource path without the name. * @see GetResourcePath(), GetName() and IsDir() */ std::string GetPath() const; /** - * Returns the resource name including the path. + * Returns the resource path including the file name. * - * @return The resource path include the name. + * @return The resource path including the file name. * @see GetPath(), GetName() and IsDir() */ std::string GetResourcePath() const; /** * Returns the base name of the resource without the path. * * Example: * \code * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); * std::string base = resource.GetBaseName(); // base = "archive" * \endcode * * @return The resource base name. * @see GetName(), GetSuffix(), GetCompleteSuffix() and GetCompleteBaseName() */ std::string GetBaseName() const; /** * Returns the complete base name of the resource without the path. * * Example: * \code * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); * std::string base = resource.GetCompleteBaseName(); // base = "archive.tar" * \endcode * * @return The resource's complete base name. * @see GetName(), GetSuffix(), GetCompleteSuffix(), and GetBaseName() */ std::string GetCompleteBaseName() const; /** * Returns the suffix of the resource. * * The suffix consists of all characters in the resource name after (but not * including) the last '.'. * * Example: * \code * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); * std::string suffix = resource.GetSuffix(); // suffix = "gz" * \endcode * * @return The resource name suffix. * @see GetName(), GetCompleteSuffix(), GetBaseName() and GetCompleteBaseName() */ std::string GetSuffix() const; /** * Returns the complete suffix of the resource. * * The suffix consists of all characters in the resource name after (but not * including) the first '.'. * * Example: * \code * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); * std::string suffix = resource.GetCompleteSuffix(); // suffix = "tar.gz" * \endcode * * @return The resource name suffix. * @see GetName(), GetSuffix(), GetBaseName(), and GetCompleteBaseName() */ std::string GetCompleteSuffix() const; /** * Returns \c true if this %ModuleResource object points to a directory and thus * may have child resources. * * @return \c true if this object points to a directory, \c false otherwise. */ bool IsDir() const; /** * Returns \c true if this %ModuleResource object points to a file resource. * * @return \c true if this object points to an embedded file, \c false otherwise. */ bool IsFile() const; /** * Returns a list of resource names which are children of this object. * * The returned names are relative to the path of this %ModuleResource object and * may contain duplicates in case of modules which are statically linked into the * module from which this object was retreived. * * @return A list of child resource names. */ std::vector GetChildren() const; /** * Returns the size of the raw embedded data for this %ModuleResource object. * * @return The resource data size. */ int GetSize() const; /** * Returns a data pointer pointing to the raw data of this %ModuleResource object. * If the resource is compressed the data returned is compressed and UncompressResourceData() * must be used to access the data. If the resource represents a directory \c 0 is returned. * * @return A raw pointer to the embedded data, or \c 0 if the resource is not a file resource. */ const unsigned char* GetData() const; private: ModuleResource(const std::string& file, ModuleResourceTree* resourceTree, const std::vector& resourceTrees); friend class Module; + friend class ModulePrivate; US_HASH_FUNCTION_FRIEND(ModuleResource); std::size_t Hash() const; ModuleResourcePrivate* d; }; US_END_NAMESPACE US_MSVC_POP_WARNING /** * \ingroup MicroServices */ US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ModuleResource)& resource); US_HASH_FUNCTION_NAMESPACE_BEGIN US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ModuleResource)) return arg.Hash(); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END #endif // USMODULERESOURCE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer.cpp b/Core/CppMicroServices/src/module/usModuleResourceBuffer.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceBuffer.cpp rename to Core/CppMicroServices/src/module/usModuleResourceBuffer.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer_p.h b/Core/CppMicroServices/src/module/usModuleResourceBuffer_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceBuffer_p.h rename to Core/CppMicroServices/src/module/usModuleResourceBuffer_p.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.cpp b/Core/CppMicroServices/src/module/usModuleResourceStream.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceStream.cpp rename to Core/CppMicroServices/src/module/usModuleResourceStream.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.h b/Core/CppMicroServices/src/module/usModuleResourceStream.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceStream.h rename to Core/CppMicroServices/src/module/usModuleResourceStream.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceTree.cpp b/Core/CppMicroServices/src/module/usModuleResourceTree.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceTree.cpp rename to Core/CppMicroServices/src/module/usModuleResourceTree.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceTree_p.h b/Core/CppMicroServices/src/module/usModuleResourceTree_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleResourceTree_p.h rename to Core/CppMicroServices/src/module/usModuleResourceTree_p.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleSettings.cpp b/Core/CppMicroServices/src/module/usModuleSettings.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleSettings.cpp rename to Core/CppMicroServices/src/module/usModuleSettings.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleSettings.h b/Core/CppMicroServices/src/module/usModuleSettings.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleSettings.h rename to Core/CppMicroServices/src/module/usModuleSettings.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp b/Core/CppMicroServices/src/module/usModuleUtils.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleUtils.cpp rename to Core/CppMicroServices/src/module/usModuleUtils.cpp diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils_p.h b/Core/CppMicroServices/src/module/usModuleUtils_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleUtils_p.h rename to Core/CppMicroServices/src/module/usModuleUtils_p.h diff --git a/Core/Code/CppMicroServices/src/module/usModuleVersion.cpp b/Core/CppMicroServices/src/module/usModuleVersion.cpp similarity index 98% rename from Core/Code/CppMicroServices/src/module/usModuleVersion.cpp rename to Core/CppMicroServices/src/module/usModuleVersion.cpp index 53550b3ea2..f27640943b 100644 --- a/Core/Code/CppMicroServices/src/module/usModuleVersion.cpp +++ b/Core/CppMicroServices/src/module/usModuleVersion.cpp @@ -1,276 +1,275 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usModuleVersion.h" #include #include #include #include #include US_BEGIN_NAMESPACE const char ModuleVersion::SEPARATOR = '.'; bool IsInvalidQualifier(char c) { return !(std::isalnum(c) || c == '_' || c == '-'); } ModuleVersion ModuleVersion::EmptyVersion() { static ModuleVersion emptyV(false); return emptyV; } ModuleVersion ModuleVersion::UndefinedVersion() { static ModuleVersion undefinedV(true); return undefinedV; } ModuleVersion& ModuleVersion::operator=(const ModuleVersion& v) { majorVersion = v.majorVersion; minorVersion = v.minorVersion; microVersion = v.microVersion; qualifier = v.qualifier; undefined = v.undefined; return *this; } ModuleVersion::ModuleVersion(bool undefined) : majorVersion(0), minorVersion(0), microVersion(0), qualifier(""), undefined(undefined) { } void ModuleVersion::Validate() { if (std::find_if(qualifier.begin(), qualifier.end(), IsInvalidQualifier) != qualifier.end()) throw std::invalid_argument(std::string("invalid qualifier: ") + qualifier); undefined = false; } ModuleVersion::ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion) : majorVersion(majorVersion), minorVersion(minorVersion), microVersion(microVersion), qualifier(""), undefined(false) { } ModuleVersion::ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion, const std::string& qualifier) : majorVersion(majorVersion), minorVersion(minorVersion), microVersion(microVersion), qualifier(qualifier), undefined(true) { this->Validate(); } ModuleVersion::ModuleVersion(const std::string& version) : majorVersion(0), minorVersion(0), microVersion(0), undefined(true) { unsigned int maj = 0; unsigned int min = 0; unsigned int mic = 0; std::string qual(""); std::vector st; std::stringstream ss(version); std::string token; while(std::getline(ss, token, SEPARATOR)) { st.push_back(token); } if (st.empty()) return; bool ok = true; ss.clear(); ss.str(st[0]); ss >> maj; ok = !ss.fail(); if (st.size() > 1) { ss.clear(); ss.str(st[1]); ss >> min; ok = !ss.fail(); if (st.size() > 2) { ss.clear(); ss.str(st[2]); ss >> mic; ok = !ss.fail(); if (st.size() > 3) { qual = st[3]; if (st.size() > 4) { ok = false; } } } } if (!ok) throw std::invalid_argument("invalid format"); majorVersion = maj; minorVersion = min; microVersion = mic; qualifier = qual; this->Validate(); } ModuleVersion::ModuleVersion(const ModuleVersion& version) : majorVersion(version.majorVersion), minorVersion(version.minorVersion), microVersion(version.microVersion), qualifier(version.qualifier), undefined(version.undefined) { } ModuleVersion ModuleVersion::ParseVersion(const std::string& version) { if (version.empty()) { return EmptyVersion(); } std::string version2(version); version2.erase(0, version2.find_first_not_of(' ')); version2.erase(version2.find_last_not_of(' ')+1); if (version2.empty()) { return EmptyVersion(); } return ModuleVersion(version2); } bool ModuleVersion::IsUndefined() const { return undefined; } unsigned int ModuleVersion::GetMajor() const { if (undefined) throw std::logic_error("Version undefined"); return majorVersion; } unsigned int ModuleVersion::GetMinor() const { if (undefined) throw std::logic_error("Version undefined"); return minorVersion; } unsigned int ModuleVersion::GetMicro() const { if (undefined) throw std::logic_error("Version undefined"); return microVersion; } std::string ModuleVersion::GetQualifier() const { if (undefined) throw std::logic_error("Version undefined"); return qualifier; } std::string ModuleVersion::ToString() const { if (undefined) return "undefined"; - std::string result; - std::stringstream ss(result); + std::stringstream ss; ss << majorVersion << SEPARATOR << minorVersion << SEPARATOR << microVersion; if (!qualifier.empty()) { ss << SEPARATOR << qualifier; } - return result; + return ss.str(); } bool ModuleVersion::operator==(const ModuleVersion& other) const { if (&other == this) { // quicktest return true; } if (other.undefined && this->undefined) return true; if (this->undefined) throw std::logic_error("Version undefined"); if (other.undefined) return false; return (majorVersion == other.majorVersion) && (minorVersion == other.minorVersion) && (microVersion == other.microVersion) && qualifier == other.qualifier; } int ModuleVersion::Compare(const ModuleVersion& other) const { if (&other == this) { // quicktest return 0; } if (this->undefined || other.undefined) throw std::logic_error("Cannot compare undefined version"); if (majorVersion < other.majorVersion) { return -1; } if (majorVersion == other.majorVersion) { if (minorVersion < other.minorVersion) { return -1; } if (minorVersion == other.minorVersion) { if (microVersion < other.microVersion) { return -1; } if (microVersion == other.microVersion) { return qualifier.compare(other.qualifier); } } } return 1; } US_END_NAMESPACE US_USE_NAMESPACE std::ostream& operator<<(std::ostream& os, const ModuleVersion& v) { return os << v.ToString(); } diff --git a/Core/Code/CppMicroServices/src/module/usModuleVersion.h b/Core/CppMicroServices/src/module/usModuleVersion.h similarity index 100% rename from Core/Code/CppMicroServices/src/module/usModuleVersion.h rename to Core/CppMicroServices/src/module/usModuleVersion.h diff --git a/Core/CppMicroServices/src/resources/manifest.json b/Core/CppMicroServices/src/resources/manifest.json new file mode 100644 index 0000000000..b2359aec43 --- /dev/null +++ b/Core/CppMicroServices/src/resources/manifest.json @@ -0,0 +1 @@ +{ "module.version" : "1.99.0" } diff --git a/Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp b/Core/CppMicroServices/src/service/usLDAPExpr.cpp similarity index 85% rename from Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp rename to Core/CppMicroServices/src/service/usLDAPExpr.cpp index 42ffde8884..9d304b8328 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp +++ b/Core/CppMicroServices/src/service/usLDAPExpr.cpp @@ -1,777 +1,822 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usLDAPExpr_p.h" +#include "usAny.h" +#include "usServicePropertiesImpl_p.h" + #include #include #include #include +#include +#include +#include + US_BEGIN_NAMESPACE const int LDAPExpr::AND = 0; const int LDAPExpr::OR = 1; const int LDAPExpr::NOT = 2; const int LDAPExpr::EQ = 4; const int LDAPExpr::LE = 8; const int LDAPExpr::GE = 16; const int LDAPExpr::APPROX = 32; const int LDAPExpr::COMPLEX = LDAPExpr::AND | LDAPExpr::OR | LDAPExpr::NOT; const int LDAPExpr::SIMPLE = LDAPExpr::EQ | LDAPExpr::LE | LDAPExpr::GE | LDAPExpr::APPROX; const LDAPExpr::Byte LDAPExpr::WILDCARD = std::numeric_limits::max(); const std::string LDAPExpr::WILDCARD_STRING = std::string(1, LDAPExpr::WILDCARD ); const std::string LDAPExpr::NULLQ = "Null query"; const std::string LDAPExpr::GARBAGE = "Trailing garbage"; const std::string LDAPExpr::EOS = "Unexpected end of query"; const std::string LDAPExpr::MALFORMED = "Malformed query"; const std::string LDAPExpr::OPERATOR = "Undefined operator"; bool stricomp(const std::string::value_type& v1, const std::string::value_type& v2) { return ::tolower(v1) == ::tolower(v2); } //! Contains the current parser position and parsing utility methods. class LDAPExpr::ParseState { private: std::size_t m_pos; std::string m_str; public: ParseState(const std::string &str); //! Move m_pos to remove the prefix \a pre bool prefix(const std::string &pre); /** Peek a char at m_pos \note If index out of bounds, throw exception */ LDAPExpr::Byte peek(); //! Increment m_pos by n void skip(int n); //! return string from m_pos until the end std::string rest() const; //! Move m_pos until there's no spaces void skipWhite(); //! Get string until special chars. Move m_pos std::string getAttributeName(); //! Get string and convert * to WILDCARD std::string getAttributeValue(); //! Throw InvalidSyntaxException exception void error(const std::string &m) const; }; class LDAPExprData : public SharedData { public: LDAPExprData( int op, const std::vector& args ) : m_operator(op), m_args(args), m_attrName(), m_attrValue() { } LDAPExprData( int op, std::string attrName, const std::string& attrValue ) : m_operator(op), m_args(), m_attrName(attrName), m_attrValue(attrValue) { } LDAPExprData( const LDAPExprData& other ) : SharedData(other), m_operator(other.m_operator), m_args(other.m_args), m_attrName(other.m_attrName), m_attrValue(other.m_attrValue) { } int m_operator; std::vector m_args; std::string m_attrName; std::string m_attrValue; }; LDAPExpr::LDAPExpr() : d() { } LDAPExpr::LDAPExpr( const std::string &filter ) : d() { ParseState ps(filter); try { LDAPExpr expr = ParseExpr(ps); if (!Trim(ps.rest()).empty()) { ps.error(GARBAGE + " '" + ps.rest() + "'"); } d = expr.d; } catch (const std::out_of_range&) { ps.error(EOS); } } LDAPExpr::LDAPExpr( int op, const std::vector& args ) : d(new LDAPExprData(op, args)) { } LDAPExpr::LDAPExpr( int op, const std::string &attrName, const std::string &attrValue ) : d(new LDAPExprData(op, attrName, attrValue)) { } LDAPExpr::LDAPExpr( const LDAPExpr& other ) : d(other.d) { } LDAPExpr& LDAPExpr::operator=(const LDAPExpr& other) { d = other.d; return *this; } LDAPExpr::~LDAPExpr() { } std::string LDAPExpr::Trim(std::string str) { str.erase(0, str.find_first_not_of(' ')); str.erase(str.find_last_not_of(' ')+1); return str; } bool LDAPExpr::GetMatchedObjectClasses(ObjectClassSet& objClasses) const { if (d->m_operator == EQ) { if (std::equal(d->m_attrName.begin(), d->m_attrName.end(), ServiceConstants::OBJECTCLASS().begin(), stricomp) && d->m_attrValue.find(WILDCARD) == std::string::npos) { objClasses.insert( d->m_attrValue ); return true; } return false; } else if (d->m_operator == AND) { bool result = false; for (std::size_t i = 0; i < d->m_args.size( ); i++) { LDAPExpr::ObjectClassSet r; if (d->m_args[i].GetMatchedObjectClasses(r)) { result = true; if (objClasses.empty()) { objClasses = r; } else { // if AND op and classes in several operands, // then only the intersection is possible. LDAPExpr::ObjectClassSet::iterator it1 = objClasses.begin(); LDAPExpr::ObjectClassSet::iterator it2 = r.begin(); while ( (it1 != objClasses.end()) && (it2 != r.end()) ) { if (*it1 < *it2) { objClasses.erase(it1++); } else if (*it2 < *it1) { ++it2; } else { // *it1 == *it2 ++it1; ++it2; } } // Anything left in set_1 from here on did not appear in set_2, // so we remove it. objClasses.erase(it1, objClasses.end()); } } } return result; } else if (d->m_operator == OR) { for (std::size_t i = 0; i < d->m_args.size( ); i++) { LDAPExpr::ObjectClassSet r; if (d->m_args[i].GetMatchedObjectClasses(r)) { std::copy(r.begin(), r.end(), std::inserter(objClasses, objClasses.begin())); } else { objClasses.clear(); return false; } } return true; } return false; } std::string LDAPExpr::ToLower(const std::string& str) { std::string lowerStr(str); std::transform(str.begin(), str.end(), lowerStr.begin(), ::tolower); return lowerStr; } bool LDAPExpr::IsSimple(const StringList& keywords, LocalCache& cache, bool matchCase ) const { if (cache.empty()) { cache.resize(keywords.size()); } if (d->m_operator == EQ) { StringList::const_iterator index; if ((index = std::find(keywords.begin(), keywords.end(), matchCase ? d->m_attrName : ToLower(d->m_attrName))) != keywords.end() && d->m_attrValue.find_first_of(WILDCARD) == std::string::npos) { cache[index - keywords.begin()] = StringList(1, d->m_attrValue); return true; } } else if (d->m_operator == OR) { for (std::size_t i = 0; i < d->m_args.size( ); i++) { if (!d->m_args[i].IsSimple(keywords, cache, matchCase)) return false; } return true; } return false; } bool LDAPExpr::IsNull() const { return !d; } -bool LDAPExpr::Query( const std::string &filter, const ServiceProperties &pd ) +bool LDAPExpr::Query( const std::string& filter, const ServicePropertiesImpl& pd) { return LDAPExpr(filter).Evaluate(pd, false); } -bool LDAPExpr::Evaluate( const ServiceProperties& p, bool matchCase ) const +bool LDAPExpr::Evaluate( const ServicePropertiesImpl& p, bool matchCase ) const { if ((d->m_operator & SIMPLE) != 0) { - Any propVal; - ServiceProperties::const_iterator it = p.find(d->m_attrName); - if (it != p.end() && (matchCase ? d->m_attrName == static_cast(it->first) : true)) - { - propVal = it->second; - } - return Compare(propVal, d->m_operator, d->m_attrValue); + // try case sensitive match first + int index = p.FindCaseSensitive(d->m_attrName); + if (index < 0 && !matchCase) index = p.Find(d->m_attrName); + return index < 0 ? false : Compare(p.Value(index), d->m_operator, d->m_attrValue); } else { // (d->m_operator & COMPLEX) != 0 switch (d->m_operator) { case AND: for (std::size_t i = 0; i < d->m_args.size(); i++) { if (!d->m_args[i].Evaluate(p, matchCase)) return false; } return true; case OR: for (std::size_t i = 0; i < d->m_args.size(); i++) { if (d->m_args[i].Evaluate(p, matchCase)) return true; } return false; case NOT: return !d->m_args[0].Evaluate(p, matchCase); default: return false; // Cannot happen } } } bool LDAPExpr::Compare( const Any& obj, int op, const std::string& s ) const { if (obj.Empty()) return false; if (op == EQ && s == WILDCARD_STRING) return true; try { const std::type_info& objType = obj.Type(); if (objType == typeid(std::string)) { return CompareString(ref_any_cast(obj), op, s); } else if (objType == typeid(std::vector)) { const std::vector& list = ref_any_cast >(obj); for (std::size_t it = 0; it != list.size(); it++) { if (CompareString(list[it], op, s)) return true; } } else if (objType == typeid(std::list)) { const std::list& list = ref_any_cast >(obj); for (std::list::const_iterator it = list.begin(); it != list.end(); ++it) { if (CompareString(*it, op, s)) return true; } } else if (objType == typeid(char)) { return CompareString(std::string(1, ref_any_cast(obj)), op, s); } else if (objType == typeid(bool)) { if (op==LE || op==GE) return false; std::string boolVal = any_cast(obj) ? "true" : "false"; return std::equal(s.begin(), s.end(), boolVal.begin(), stricomp); } - else if (objType == typeid(Byte) || objType == typeid(int)) + else if (objType == typeid(short)) { - int sInt; - std::stringstream ss(s); - ss >> sInt; - int intVal = any_cast(obj); - - switch(op) - { - case LE: - return intVal <= sInt; - case GE: - return intVal >= sInt; - default: /*APPROX and EQ*/ - return intVal == sInt; - } + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(long int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(long long int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned char)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned short)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned long int)) + { + return CompareIntegralType(obj, op, s); + } + else if (objType == typeid(unsigned long long int)) + { + return CompareIntegralType(obj, op, s); } else if (objType == typeid(float)) { - float sFloat; - std::stringstream ss(s); - ss >> sFloat; - float floatVal = any_cast(obj); + errno = 0; + char* endptr = 0; + double sFloat = strtod(s.c_str(), &endptr); + if ((errno == ERANGE && (sFloat == 0 || sFloat == HUGE_VAL || sFloat == -HUGE_VAL)) || + (errno != 0 && sFloat == 0) || endptr == s.c_str()) + { + return false; + } + + double floatVal = static_cast(any_cast(obj)); switch(op) { case LE: return floatVal <= sFloat; case GE: return floatVal >= sFloat; default: /*APPROX and EQ*/ - float diff = floatVal - sFloat; + double diff = floatVal - sFloat; return (diff < std::numeric_limits::epsilon()) && (diff > -std::numeric_limits::epsilon()); } } else if (objType == typeid(double)) { - double sDouble; - std::stringstream ss(s); - ss >> sDouble; + errno = 0; + char* endptr = 0; + double sDouble = strtod(s.c_str(), &endptr); + if ((errno == ERANGE && (sDouble == 0 || sDouble == HUGE_VAL || sDouble == -HUGE_VAL)) || + (errno != 0 && sDouble == 0) || endptr == s.c_str()) + { + return false; + } + double doubleVal = any_cast(obj); switch(op) { case LE: return doubleVal <= sDouble; case GE: return doubleVal >= sDouble; default: /*APPROX and EQ*/ double diff = doubleVal - sDouble; return (diff < std::numeric_limits::epsilon()) && (diff > -std::numeric_limits::epsilon()); } } - else if (objType == typeid(long long int)) - { - long long int sLongInt; - std::stringstream ss(s); - ss >> sLongInt; - long long int longIntVal = any_cast(obj); - - switch(op) - { - case LE: - return longIntVal <= sLongInt; - case GE: - return longIntVal >= sLongInt; - default: /*APPROX and EQ*/ - return longIntVal == sLongInt; - } - } else if (objType == typeid(std::vector)) { const std::vector& list = ref_any_cast >(obj); for (std::size_t it = 0; it != list.size(); it++) { if (Compare(list[it], op, s)) return true; } } } catch (...) { // This might happen if a std::string-to-datatype conversion fails // Just consider it a false match and ignore the exception } return false; } +template +bool LDAPExpr::CompareIntegralType(const Any& obj, const int op, const std::string& s) const +{ + errno = 0; + char* endptr = 0; + long longInt = strtol(s.c_str(), &endptr, 10); + if ((errno == ERANGE && (longInt == std::numeric_limits::max() || longInt == std::numeric_limits::min())) || + (errno != 0 && longInt == 0) || endptr == s.c_str()) + { + return false; + } + + T sInt = static_cast(longInt); + T intVal = any_cast(obj); + + switch(op) + { + case LE: + return intVal <= sInt; + case GE: + return intVal >= sInt; + default: /*APPROX and EQ*/ + return intVal == sInt; + } +} + bool LDAPExpr::CompareString( const std::string& s1, int op, const std::string& s2 ) { switch(op) { case LE: return s1.compare(s2) <= 0; case GE: return s1.compare(s2) >= 0; case EQ: return PatSubstr(s1,s2); case APPROX: return FixupString(s2) == FixupString(s1); default: return false; } } std::string LDAPExpr::FixupString( const std::string& s ) { std::string sb; + sb.reserve(s.size()); std::size_t len = s.length(); for(std::size_t i=0; im_operator std::vector v; do { v.push_back(ParseExpr(ps)); ps.skipWhite(); } while (ps.peek() == '('); std::size_t n = v.size(); if (!ps.prefix(")") || n == 0 || (op == NOT && n > 1)) ps.error(MALFORMED); return LDAPExpr(op, v); } LDAPExpr LDAPExpr::ParseSimple( ParseState &ps ) { std::string attrName = ps.getAttributeName(); if (attrName.empty()) ps.error(MALFORMED); int op = 0; if (ps.prefix("=")) op = EQ; else if (ps.prefix("<=")) op = LE; else if(ps.prefix(">=")) op = GE; else if(ps.prefix("~=")) op = APPROX; else { // System.out.println("undef op='" + ps.peek() + "'"); ps.error(OPERATOR); // Does not return } std::string attrValue = ps.getAttributeValue(); if (!ps.prefix(")")) ps.error(MALFORMED); return LDAPExpr(op, attrName, attrValue); } const std::string LDAPExpr::ToString() const { std::string res; res.append("("); if ((d->m_operator & SIMPLE) != 0) { res.append(d->m_attrName); switch (d->m_operator) { case EQ: res.append("="); break; case LE: res.append("<="); break; case GE: res.append(">="); break; case APPROX: res.append("~="); break; } for (std::size_t i = 0; i < d->m_attrValue.length(); i++) { Byte c = d->m_attrValue.at(i); if (c == '(' || c == ')' || c == '*' || c == '\\') { res.append(1, '\\'); } else if (c == WILDCARD) { c = '*'; } res.append(1, c); } } else { switch (d->m_operator) { case AND: res.append("&"); break; case OR: res.append("|"); break; case NOT: res.append("!"); break; } for (std::size_t i = 0; i < d->m_args.size(); i++) { res.append(d->m_args[i].ToString()); } } res.append(")"); return res; } LDAPExpr::ParseState::ParseState( const std::string& str ) : m_pos(0), m_str() { if (str.empty()) { error(NULLQ); } m_str = str; } bool LDAPExpr::ParseState::prefix( const std::string& pre ) { std::string::iterator startIter = m_str.begin() + m_pos; if (!std::equal(pre.begin(), pre.end(), startIter)) return false; m_pos += pre.size(); return true; } char LDAPExpr::ParseState::peek() { if ( m_pos >= m_str.size() ) { throw std::out_of_range( "LDAPExpr" ); } return m_str.at(m_pos); } void LDAPExpr::ParseState::skip( int n ) { m_pos += n; } std::string LDAPExpr::ParseState::rest() const { return m_str.substr(m_pos); } void LDAPExpr::ParseState::skipWhite() { while (std::isspace(peek())) { m_pos++; } } std::string LDAPExpr::ParseState::getAttributeName() { std::size_t start = m_pos; std::size_t n = 0; bool nIsSet = false; for(;; m_pos++) { Byte c = peek(); if (c == '(' || c == ')' || c == '<' || c == '>' || c == '=' || c == '~') { break; } else if (!std::isspace(c)) { n = m_pos - start + 1; nIsSet = true; } } if (!nIsSet) { return std::string(); } return m_str.substr(start, n); } std::string LDAPExpr::ParseState::getAttributeValue() { std::string sb; bool exit = false; while( !exit ) { Byte c = peek( ); switch(c) { case '(': case ')': exit = true; break; case '*': sb.append(1, WILDCARD); break; case '\\': sb.append(1, m_str.at(++m_pos)); break; default: sb.append(1, c); break; } if ( !exit ) { m_pos++; } } return sb; } void LDAPExpr::ParseState::error( const std::string &m ) const { std::string errorStr = m + ": " + (m_str.empty() ? "" : m_str.substr(m_pos)); throw std::invalid_argument(errorStr); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h b/Core/CppMicroServices/src/service/usLDAPExpr_p.h similarity index 95% rename from Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h rename to Core/CppMicroServices/src/service/usLDAPExpr_p.h index d6dcb67d10..2791c08a2d 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h +++ b/Core/CppMicroServices/src/service/usLDAPExpr_p.h @@ -1,183 +1,188 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USLDAPEXPR_H #define USLDAPEXPR_H #include #include "usSharedData.h" -#include "usServiceProperties.h" #include #include US_BEGIN_NAMESPACE +class Any; class LDAPExprData; +class ServicePropertiesImpl; /** * This class is not part of the public API. */ class LDAPExpr { public: const static int AND; // = 0; const static int OR; // = 1; const static int NOT; // = 2; const static int EQ; // = 4; const static int LE; // = 8; const static int GE; // = 16; const static int APPROX; // = 32; const static int COMPLEX; // = AND | OR | NOT; const static int SIMPLE; // = EQ | LE | GE | APPROX; typedef char Byte; typedef std::vector StringList; typedef std::vector LocalCache; typedef US_UNORDERED_SET_TYPE ObjectClassSet; /** * Creates an invalid LDAPExpr object. Use with care. * * @see IsNull() */ LDAPExpr(); LDAPExpr(const std::string& filter); LDAPExpr(const LDAPExpr& other); LDAPExpr& operator=(const LDAPExpr& other); ~LDAPExpr(); /** * Get object class set matched by this LDAP expression. This will not work * with wildcards and NOT expressions. If a set can not be determined return false. * * \param objClasses The set of matched classes will be added to objClasses. * \return If the set cannot be determined, false is returned, true otherwise. */ bool GetMatchedObjectClasses(ObjectClassSet& objClasses) const; /** * Checks if this LDAP expression is "simple". The definition of * a simple filter is: *

    *
  • (name=value) is simple if * name is a member of the provided keywords, * and value does not contain a wildcard character;
  • *
  • (| EXPR+ ) is simple if all EXPR * expressions are simple;
  • *
  • No other expressions are simple.
  • *
* If the filter is found to be simple, the cache is * filled with mappings from the provided keywords to lists * of attribute values. The keyword-value-pairs are the ones that * satisfy this expression, for the given keywords. * * @param keywords The keywords to look for. * @param cache An array (indexed by the keyword indexes) of lists to * fill in with values saturating this expression. * @return true if this expression is simple, * false otherwise. */ bool IsSimple( const StringList& keywords, LocalCache& cache, bool matchCase) const; /** * Returns true if this instance is invalid, i.e. it was * constructed using LDAPExpr(). * * @return true if the expression is invalid, * false otherwise. */ bool IsNull() const; //! - static bool Query(const std::string& filter, const ServiceProperties& pd); + static bool Query(const std::string& filter, const ServicePropertiesImpl& pd); //! Evaluate this LDAP filter. - bool Evaluate(const ServiceProperties& p, bool matchCase) const; + bool Evaluate(const ServicePropertiesImpl& p, bool matchCase) const; //! const std::string ToString() const; private: class ParseState; //! LDAPExpr(int op, const std::vector& args); //! LDAPExpr(int op, const std::string& attrName, const std::string& attrValue); //! static LDAPExpr ParseExpr(ParseState& ps); //! static LDAPExpr ParseSimple(ParseState& ps); static std::string Trim(std::string str); static std::string ToLower(const std::string& str); //! bool Compare(const Any& obj, int op, const std::string& s) const; + //! + template + bool CompareIntegralType(const Any& obj, const int op, const std::string& s) const; + //! static bool CompareString(const std::string& s1, int op, const std::string& s2); //! static std::string FixupString(const std::string &s); //! static bool PatSubstr(const std::string& s, const std::string& pat); //! static bool PatSubstr(const std::string& s, int si, const std::string& pat, int pi); const static Byte WILDCARD; // = 65535; const static std::string WILDCARD_STRING;// = std::string( WILDCARD ); const static std::string NULLQ; // = "Null query"; const static std::string GARBAGE; // = "Trailing garbage"; const static std::string EOS; // = "Unexpected end of query"; const static std::string MALFORMED; // = "Malformed query"; const static std::string OPERATOR; // = "Undefined m_operator"; //! Shared pointer SharedDataPointer d; }; US_END_NAMESPACE #endif // USLDAPEXPR_H diff --git a/Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp b/Core/CppMicroServices/src/service/usLDAPFilter.cpp similarity index 87% rename from Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp rename to Core/CppMicroServices/src/service/usLDAPFilter.cpp index c8a94d656e..36d124e656 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp +++ b/Core/CppMicroServices/src/service/usLDAPFilter.cpp @@ -1,119 +1,121 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usLDAPFilter.h" #include "usLDAPExpr_p.h" -#include "usServiceReferencePrivate.h" +#include "usServicePropertiesImpl_p.h" +#include "usServiceReference.h" +#include "usServiceReferenceBasePrivate.h" #include US_BEGIN_NAMESPACE class LDAPFilterData : public SharedData { public: LDAPFilterData() : ldapExpr() {} LDAPFilterData(const std::string& filter) : ldapExpr(filter) {} LDAPFilterData(const LDAPFilterData& other) : SharedData(other), ldapExpr(other.ldapExpr) {} LDAPExpr ldapExpr; }; LDAPFilter::LDAPFilter() : d(0) { } LDAPFilter::LDAPFilter(const std::string& filter) : d(0) { try { d = new LDAPFilterData(filter); } catch (const std::exception& e) { throw std::invalid_argument(e.what()); } } LDAPFilter::LDAPFilter(const LDAPFilter& other) : d(other.d) { } LDAPFilter::~LDAPFilter() { } LDAPFilter::operator bool() const { return d.ConstData() != 0; } -bool LDAPFilter::Match(const ServiceReference& reference) const +bool LDAPFilter::Match(const ServiceReferenceBase& reference) const { return d->ldapExpr.Evaluate(reference.d->GetProperties(), true); } bool LDAPFilter::Match(const ServiceProperties& dictionary) const { - return d->ldapExpr.Evaluate(dictionary, false); + return d->ldapExpr.Evaluate(ServicePropertiesImpl(dictionary), false); } bool LDAPFilter::MatchCase(const ServiceProperties& dictionary) const { - return d->ldapExpr.Evaluate(dictionary, true); + return d->ldapExpr.Evaluate(ServicePropertiesImpl(dictionary), true); } std::string LDAPFilter::ToString() const { return d->ldapExpr.ToString(); } bool LDAPFilter::operator==(const LDAPFilter& other) const { return d->ldapExpr.ToString() == other.d->ldapExpr.ToString(); } LDAPFilter& LDAPFilter::operator=(const LDAPFilter& filter) { d = filter.d; return *this; } US_END_NAMESPACE US_USE_NAMESPACE std::ostream& operator<<(std::ostream& os, const LDAPFilter& filter) { return os << filter.ToString(); } diff --git a/Core/Code/CppMicroServices/src/service/usLDAPFilter.h b/Core/CppMicroServices/src/service/usLDAPFilter.h similarity index 98% rename from Core/Code/CppMicroServices/src/service/usLDAPFilter.h rename to Core/CppMicroServices/src/service/usLDAPFilter.h index c8355fc3be..d8df499a70 100644 --- a/Core/Code/CppMicroServices/src/service/usLDAPFilter.h +++ b/Core/CppMicroServices/src/service/usLDAPFilter.h @@ -1,174 +1,174 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USLDAPFILTER_H #define USLDAPFILTER_H -#include "usServiceReference.h" #include "usServiceProperties.h" #include "usSharedData.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4251) #endif US_BEGIN_NAMESPACE class LDAPFilterData; +class ServiceReferenceBase; /** * \ingroup MicroServices * * An RFC 1960-based Filter. * *

* A LDAPFilter can be used numerous times to determine if the match * argument matches the filter string that was used to create the LDAPFilter. *

* Some examples of LDAP filters are: * * - "(cn=Babs Jensen)" * - "(!(cn=Tim Howes))" * - "(&(" + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))" * - "(o=univ*of*mich*)" * * \remarks This class is thread safe. */ class US_EXPORT LDAPFilter { public: /** * Creates in invalid LDAPFilter object. * Test the validity by using the boolean conversion operator. * *

* Calling methods on an invalid LDAPFilter * will result in undefined behavior. */ LDAPFilter(); /** * Creates a LDAPFilter object. This LDAPFilter * object may be used to match a ServiceReference object or a * ServiceProperties object. * *

* If the filter cannot be parsed, an std::invalid_argument will be * thrown with a human readable message where the filter became unparsable. * * @param filter The filter string. * @return A LDAPFilter object encapsulating the filter string. * @throws std::invalid_argument If filter contains an invalid * filter string that cannot be parsed. * @see "Framework specification for a description of the filter string syntax." TODO! */ LDAPFilter(const std::string& filter); LDAPFilter(const LDAPFilter& other); ~LDAPFilter(); operator bool() const; /** * Filter using a service's properties. *

* This LDAPFilter is executed using the keys and values of the * referenced service's properties. The keys are looked up in a case * insensitive manner. * * @param reference The reference to the service whose properties are used * in the match. * @return true if the service's properties match this * LDAPFilter false otherwise. */ - bool Match(const ServiceReference& reference) const; + bool Match(const ServiceReferenceBase& reference) const; /** * Filter using a ServiceProperties object with case insensitive key lookup. This * LDAPFilter is executed using the specified ServiceProperties's keys * and values. The keys are looked up in a case insensitive manner. * * @param dictionary The ServiceProperties whose key/value pairs are used * in the match. * @return true if the ServiceProperties's values match this * filter; false otherwise. */ bool Match(const ServiceProperties& dictionary) const; /** * Filter using a ServiceProperties. This LDAPFilter is executed using * the specified ServiceProperties's keys and values. The keys are looked * up in a normal manner respecting case. * * @param dictionary The ServiceProperties whose key/value pairs are used * in the match. * @return true if the ServiceProperties's values match this * filter; false otherwise. */ bool MatchCase(const ServiceProperties& dictionary) const; /** * Returns this LDAPFilter's filter string. *

* The filter string is normalized by removing whitespace which does not * affect the meaning of the filter. * * @return This LDAPFilter's filter string. */ std::string ToString() const; /** * Compares this LDAPFilter to another LDAPFilter. * *

* This implementation returns the result of calling * this->ToString() == other.ToString(). * * @param other The object to compare against this LDAPFilter. * @return Returns the result of calling * this->ToString() == other.ToString(). */ bool operator==(const LDAPFilter& other) const; LDAPFilter& operator=(const LDAPFilter& filter); protected: SharedDataPointer d; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif /** * \ingroup MicroServices */ US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(LDAPFilter)& filter); #endif // USLDAPFILTER_H diff --git a/Core/CppMicroServices/src/service/usPrototypeServiceFactory.h b/Core/CppMicroServices/src/service/usPrototypeServiceFactory.h new file mode 100644 index 0000000000..080f1fe286 --- /dev/null +++ b/Core/CppMicroServices/src/service/usPrototypeServiceFactory.h @@ -0,0 +1,102 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USPROTOTYPESERVICEFACTORY_H +#define USPROTOTYPESERVICEFACTORY_H + +#include + +US_BEGIN_NAMESPACE + +/** + * @ingroup MicroServices + * + * A factory for \link ServiceConstants::SCOPE_PROTOTYPE prototype scope\endlink services. + * The factory can provide multiple, unique service objects. + * + * When registering a service, a PrototypeServiceFactory object can be used + * instead of a service object, so that the module developer can create a + * unique service object for each caller that is using the service. + * When a caller uses a ServiceObjects to request a service instance, the + * framework calls the GetService method to return a service object specifically + * for the requesting caller. The caller can release the returned service object + * and the framework will call the UngetService method with the service object. + * When a module uses the ModuleContext::GetService(const ServiceReferenceBase&) + * method to obtain a service object, the framework acts as if the service + * has module scope. That is, the framework will call the GetService method to + * obtain a module-scoped instance which will be cached and have a use count. + * See ServiceFactory. + * + * A module can use both ServiceObjects and ModuleContext::GetService(const ServiceReferenceBase&) + * to obtain a service object for a service. ServiceObjects::GetService() will always + * return an instance provided by a call to GetService(Module*, const ServiceRegistrationBase&) + * and ModuleContext::GetService(const ServiceReferenceBase&) will always + * return the module-scoped instance. + * PrototypeServiceFactory objects are only used by the framework and are not made + * available to other modules. The framework may concurrently call a PrototypeServiceFactory. + * + * @see ModuleContext::GetServiceObjects() + * @see ServiceObjects + */ +struct PrototypeServiceFactory : public ServiceFactory +{ + + /** + * Returns a service object for a caller. + * + * The framework invokes this method for each caller requesting a service object using + * ServiceObjects::GetService(). The factory can then return a specific service object for the caller. + * The framework checks that the returned service object is valid. If the returned service + * object is empty or does not contain entries for all the interfaces named when the service + * was registered, a warning is issued and NULL is returned to the caller. If this + * method throws an exception, a warning is issued and NULL is returned to the caller. + * + * @param module The module requesting the service. + * @param registration The ServiceRegistrationBase object for the requested service. + * @return A service object that must contain entries for all the interfaces named when + * the service was registered. + * + * @see ServiceObjects#GetService() + * @see InterfaceMap + */ + virtual InterfaceMap GetService(Module* module, const ServiceRegistrationBase& registration) = 0; + + /** + * Releases a service object created for a caller. + * + * The framework invokes this method when a service has been released by a modules such as + * by calling ServiceObjects::UngetService(). The service object may then be destroyed. + * If this method throws an exception, a warning is issued. + * + * @param module The module releasing the service. + * @param registration The ServiceRegistrationBase object for the service being released. + * @param service The service object returned by a previous call to the GetService method. + * + * @see ServiceObjects::UngetService() + */ + virtual void UngetService(Module* module, const ServiceRegistrationBase& registration, + const InterfaceMap& service) = 0; + +}; + +US_END_NAMESPACE + +#endif // USPROTOTYPESERVICEFACTORY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceEvent.cpp b/Core/CppMicroServices/src/service/usServiceEvent.cpp similarity index 89% rename from Core/Code/CppMicroServices/src/service/usServiceEvent.cpp rename to Core/CppMicroServices/src/service/usServiceEvent.cpp index 7582409df8..e1b88f64f4 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceEvent.cpp +++ b/Core/CppMicroServices/src/service/usServiceEvent.cpp @@ -1,132 +1,132 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usServiceEvent.h" #include "usServiceProperties.h" US_BEGIN_NAMESPACE class ServiceEventData : public SharedData { public: - ServiceEventData(const ServiceEvent::Type& type, const ServiceReference& reference) + ServiceEventData(const ServiceEvent::Type& type, const ServiceReferenceBase& reference) : type(type), reference(reference) { } ServiceEventData(const ServiceEventData& other) : SharedData(other), type(other.type), reference(other.reference) { } const ServiceEvent::Type type; - const ServiceReference reference; + const ServiceReferenceBase reference; private: // purposely not implemented ServiceEventData& operator=(const ServiceEventData&); }; ServiceEvent::ServiceEvent() : d(0) { } ServiceEvent::~ServiceEvent() { } bool ServiceEvent::IsNull() const { return !d; } -ServiceEvent::ServiceEvent(Type type, const ServiceReference& reference) +ServiceEvent::ServiceEvent(Type type, const ServiceReferenceBase& reference) : d(new ServiceEventData(type, reference)) { } ServiceEvent::ServiceEvent(const ServiceEvent& other) : d(other.d) { } ServiceEvent& ServiceEvent::operator=(const ServiceEvent& other) { d = other.d; return *this; } -ServiceReference ServiceEvent::GetServiceReference() const +ServiceReferenceU ServiceEvent::GetServiceReference() const { return d->reference; } ServiceEvent::Type ServiceEvent::GetType() const { return d->type; } US_END_NAMESPACE US_USE_NAMESPACE std::ostream& operator<<(std::ostream& os, const ServiceEvent::Type& type) { switch(type) { case ServiceEvent::MODIFIED: return os << "MODIFIED"; case ServiceEvent::MODIFIED_ENDMATCH: return os << "MODIFIED_ENDMATCH"; case ServiceEvent::REGISTERED: return os << "REGISTERED"; case ServiceEvent::UNREGISTERING: return os << "UNREGISTERING"; default: return os << "unknown service event type (" << static_cast(type) << ")"; } } std::ostream& operator<<(std::ostream& os, const ServiceEvent& event) { if (event.IsNull()) return os << "NONE"; os << event.GetType(); - ServiceReference sr = event.GetServiceReference(); + ServiceReferenceU sr = event.GetServiceReference(); if (sr) { // Some events will not have a service reference long int sid = any_cast(sr.GetProperty(ServiceConstants::SERVICE_ID())); os << " " << sid; Any classes = sr.GetProperty(ServiceConstants::OBJECTCLASS()); - os << " objectClass=" << classes << ")"; + os << " objectClass=" << classes.ToString() << ")"; } return os; } diff --git a/Core/Code/CppMicroServices/src/service/usServiceEvent.h b/Core/CppMicroServices/src/service/usServiceEvent.h similarity index 95% rename from Core/Code/CppMicroServices/src/service/usServiceEvent.h rename to Core/CppMicroServices/src/service/usServiceEvent.h index 1d181deed2..f5e2d45b17 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceEvent.h +++ b/Core/CppMicroServices/src/service/usServiceEvent.h @@ -1,191 +1,197 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICEEVENT_H #define USSERVICEEVENT_H #ifdef REGISTERED #ifdef _WIN32 #error The REGISTERED preprocessor define clashes with the ServiceEvent::REGISTERED\ enum type. Try to reorder your includes, compile with WIN32_LEAN_AND_MEAN, or undef\ the REGISTERED macro befor including this header. #else #error The REGISTERED preprocessor define clashes with the ServiceEvent::REGISTERED\ enum type. Try to reorder your includes or undef the REGISTERED macro befor including\ this header. #endif #endif #include "usSharedData.h" #include "usServiceReference.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4251) #endif US_BEGIN_NAMESPACE class ServiceEventData; /** * \ingroup MicroServices * * An event from the Micro Services framework describing a service lifecycle change. *

* ServiceEvent objects are delivered to * listeners connected via ModuleContext::AddServiceListener() when a * change occurs in this service's lifecycle. A type code is used to identify * the event type for future extendability. */ class US_EXPORT ServiceEvent { SharedDataPointer d; public: enum Type { /** * This service has been registered. *

* This event is delivered after the service * has been registered with the framework. * * @see ModuleContext#RegisterService() */ REGISTERED = 0x00000001, /** * The properties of a registered service have been modified. *

* This event is delivered after the service * properties have been modified. * * @see ServiceRegistration#SetProperties */ MODIFIED = 0x00000002, /** * This service is in the process of being unregistered. *

* This event is delivered before the service * has completed unregistering. * *

* If a module is using a service that is UNREGISTERING, the * module should release its use of the service when it receives this event. * If the module does not release its use of the service when it receives * this event, the framework will automatically release the module's use of * the service while completing the service unregistration operation. * * @see ServiceRegistration#Unregister * @see ModuleContext#UngetService */ UNREGISTERING = 0x00000004, /** * The properties of a registered service have been modified and the new * properties no longer match the listener's filter. *

* This event is delivered after the service * properties have been modified. This event is only delivered to listeners * which were added with a non-empty filter where the filter * matched the service properties prior to the modification but the filter * does not match the modified service properties. * * @see ServiceRegistration#SetProperties */ MODIFIED_ENDMATCH = 0x00000008 }; /** * Creates an invalid instance. */ ServiceEvent(); ~ServiceEvent(); /** * Can be used to check if this ServiceEvent instance is valid, * or if it has been constructed using the default constructor. * * @return true if this event object is valid, * false otherwise. */ bool IsNull() const; /** * Creates a new service event object. * * @param type The event type. * @param reference A ServiceReference object to the service * that had a lifecycle change. */ - ServiceEvent(Type type, const ServiceReference& reference); + ServiceEvent(Type type, const ServiceReferenceBase& reference); ServiceEvent(const ServiceEvent& other); ServiceEvent& operator=(const ServiceEvent& other); /** * Returns a reference to the service that had a change occur in its * lifecycle. *

* This reference is the source of the event. * * @return Reference to the service that had a lifecycle change. */ - ServiceReference GetServiceReference() const; + ServiceReferenceU GetServiceReference() const; + + template + ServiceReference GetServiceReference(InterfaceT) const + { + return GetServiceReference(); + } /** * Returns the type of event. The event type values are: *

    *
  • {@link #REGISTERED}
  • *
  • {@link #MODIFIED}
  • *
  • {@link #MODIFIED_ENDMATCH}
  • *
  • {@link #UNREGISTERING}
  • *
* * @return Type of service lifecycle change. */ Type GetType() const; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif /** * \ingroup MicroServices * @{ */ US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceEvent::Type)& type); US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceEvent)& event); /** @}*/ #endif // USSERVICEEVENT_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceException.cpp b/Core/CppMicroServices/src/service/usServiceException.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/service/usServiceException.cpp rename to Core/CppMicroServices/src/service/usServiceException.cpp diff --git a/Core/Code/CppMicroServices/src/service/usServiceException.h b/Core/CppMicroServices/src/service/usServiceException.h similarity index 100% rename from Core/Code/CppMicroServices/src/service/usServiceException.h rename to Core/CppMicroServices/src/service/usServiceException.h diff --git a/Core/Code/CppMicroServices/src/service/usServiceFactory.h b/Core/CppMicroServices/src/service/usServiceFactory.h similarity index 76% rename from Core/Code/CppMicroServices/src/service/usServiceFactory.h rename to Core/CppMicroServices/src/service/usServiceFactory.h index 84c589e768..0d8076ae6d 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceFactory.h +++ b/Core/CppMicroServices/src/service/usServiceFactory.h @@ -1,111 +1,119 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ +#ifndef USSERVICEFACTORY_H +#define USSERVICEFACTORY_H +#include "usServiceInterface.h" #include "usServiceRegistration.h" US_BEGIN_NAMESPACE /** * \ingroup MicroServices * - * Allows services to provide customized service objects in the module - * environment. + * A factory for \link ServiceConstants::SCOPE_MODULE module scope\endlink services. + * The factory can provide service objects unique to each module. * *

* When registering a service, a ServiceFactory object can be * used instead of a service object, so that the module developer can gain * control of the specific service object granted to a module that is using the * service. * *

* When this happens, the * ModuleContext::GetService(const ServiceReference&) method calls the * ServiceFactory::GetService method to create a service object * specifically for the requesting module. The service object returned by the * ServiceFactory is cached by the framework until the module * releases its use of the service. * *

* When the module's use count for the service equals zero (including the module * unloading or the service being unregistered), the * ServiceFactory::UngetService method is called. * *

* ServiceFactory objects are only used by the framework and are * not made available to other modules in the module environment. The framework * may concurrently call a ServiceFactory. * * @see ModuleContext#GetService + * @see PrototypeServiceFactory * @remarks This class is thread safe. */ class ServiceFactory { public: virtual ~ServiceFactory() {} /** * Creates a new service object. * *

* The Framework invokes this method the first time the specified * module requests a service object using the - * ModuleContext::GetService(const ServiceReference&) method. The + * ModuleContext::GetService(const ServiceReferenceBase&) method. The * service factory can then return a specific service object for each * module. * *

- * The framework caches the value returned (unless it is 0), + * The framework caches the value returned (unless the InterfaceMap is empty), * and will return the same service object on any future call to * ModuleContext::GetService for the same modules. This means the - * framework must not allow this method to be concurrently called for the + * framework does not allow this method to be concurrently called for the * same module. * * @param module The module using the service. - * @param registration The ServiceRegistration object for the + * @param registration The ServiceRegistrationBase object for the * service. - * @return A service object that must be an instance of all - * the classes named when the service was registered. + * @return A service object that must contain entries for all + * the interfaces named when the service was registered. * @see ModuleContext#GetService + * @see InterfaceMap */ - virtual US_BASECLASS_NAME* GetService(Module* module, const ServiceRegistration& registration) = 0; + virtual InterfaceMap GetService(Module* module, const ServiceRegistrationBase& registration) = 0; /** * Releases a service object. * *

* The framework invokes this method when a service has been released by a * module. The service object may then be destroyed. * * @param module The Module releasing the service. * @param registration The ServiceRegistration object for the * service. * @param service The service object returned by a previous call to the * ServiceFactory::GetService method. * @see ModuleContext#UngetService + * @see InterfaceMap */ - virtual void UngetService(Module* module, const ServiceRegistration& registration, - US_BASECLASS_NAME* service) = 0; + virtual void UngetService(Module* module, const ServiceRegistrationBase& registration, + const InterfaceMap& service) = 0; }; US_END_NAMESPACE + +#endif // USSERVICEFACTORY_H diff --git a/Core/CppMicroServices/src/service/usServiceInterface.h b/Core/CppMicroServices/src/service/usServiceInterface.h new file mode 100644 index 0000000000..91efe207ff --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceInterface.h @@ -0,0 +1,342 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef USSERVICEINTERFACE_H +#define USSERVICEINTERFACE_H + +#include +#include + +#include +#include +#include + +/** + * \ingroup MicroServices + * + * Returns a unique id for a given type. + * + * This template method is specialized in the macro + * #US_DECLARE_SERVICE_INTERFACE to return a unique id + * for each service interface. + * + * @tparam T The service interface type. + * @return A unique id for the service interface type T. + */ +template inline const char* us_service_interface_iid(); + +/// \cond +template<> inline const char* us_service_interface_iid() { return ""; } +/// \endcond + +#if defined(QT_DEBUG) || defined(QT_NO_DEBUG) +#include + +#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ + template<> inline const char* qobject_interface_iid<_service_interface_type*>() \ + { return _service_interface_id; } \ + template<> inline const char* us_service_interface_iid<_service_interface_type>() \ + { return _service_interface_id; } \ + template<> inline _service_interface_type* qobject_cast<_service_interface_type*>(QObject* object) \ + { return reinterpret_cast<_service_interface_type*>(object ? object->qt_metacast(_service_interface_id) : 0); } \ + template<> inline _service_interface_type* qobject_cast<_service_interface_type*>(const QObject* object) \ + { return reinterpret_cast<_service_interface_type*>(object ? const_cast(object)->qt_metacast(_service_interface_id) : 0); } + +#else + +/** + * \ingroup MicroServices + * + * \brief Declare a CppMicroServices service interface. + * + * This macro associates the given identifier \e _service_interface_id (a string literal) to the + * interface class called _service_interface_type. The Identifier must be unique. For example: + * + * \code + * #include + * + * struct ISomeInterace { ... }; + * + * US_DECLARE_SERVICE_INTERFACE(ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") + * \endcode + * + * This macro is normally used right after the class definition for _service_interface_type, in a header file. + * + * If you want to use #US_DECLARE_SERVICE_INTERFACE with interface classes declared in a + * namespace then you have to make sure the #US_DECLARE_SERVICE_INTERFACE macro call is not + * inside a namespace though. For example: + * + * \code + * #include + * + * namespace Foo + * { + * struct ISomeInterface { ... }; + * } + * + * US_DECLARE_SERVICE_INTERFACE(Foo::ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") + * \endcode + * + * @param _service_interface_type The service interface type. + * @param _service_interface_id A string literal representing a globally unique identifier. + */ +#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ + template<> inline const char* us_service_interface_iid<_service_interface_type>() \ + { return _service_interface_id; } \ + +#endif + +US_BEGIN_NAMESPACE + +class ServiceFactory; + +/** + * @ingroup MicroServices + * + * A helper type used in several methods to get proper + * method overload resolutions. + */ +template +struct InterfaceT {}; + +/** + * @ingroup MicroServices + * + * A map containing interfaces ids and their corresponding service object + * pointers. InterfaceMap instances represent a complete service object + * which implementes one or more service interfaces. For each implemented + * service interface, there is an entry in the map with the key being + * the service interface id and the value a pointer to the service + * interface implementation. + * + * To create InterfaceMap instances, use the MakeInterfaceMap helper class. + * + * @note This is a low-level type and should only rarely be used. + * + * @see MakeInterfaceMap + */ +typedef std::map InterfaceMap; + + +template +bool InsertInterfaceType(InterfaceMap& im, I* i) +{ + if (us_service_interface_iid() == NULL) + { + throw ServiceException(std::string("The interface class ") + typeid(I).name() + + " uses an invalid id in its US_DECLARE_SERVICE_INTERFACE macro call."); + } + im.insert(std::make_pair(std::string(us_service_interface_iid()), + static_cast(static_cast(i)))); + return true; +} + +template<> +inline bool InsertInterfaceType(InterfaceMap&, void*) +{ + return false; +} + + +/** + * @ingroup MicroServices + * + * Helper class for constructing InterfaceMap instances based + * on service implementations or service factories. + * + * Example usage: + * \code + * MyService service; // implementes I1 and I2 + * InterfaceMap im = MakeInterfaceMap(&service); + * \endcode + * + * The MakeInterfaceMap supports service implementations with + * up to three service interfaces. + * + * @see InterfaceMap + */ +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + I2* m_interface2; + I3* m_interface3; + + /** + * Constructor taking a service implementation pointer. + * + * @param impl A service implementation pointer, which must + * be castable to a all specified service interfaces. + */ + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + , m_interface2(static_cast(impl)) + , m_interface3(static_cast(impl)) + {} + + /** + * Constructor taking a service factory. + * + * @param factory A service factory. + */ + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + , m_interface2(NULL) + , m_interface3(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + InsertInterfaceType(sim, m_interface2); + InsertInterfaceType(sim, m_interface3); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +/// \cond +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + I2* m_interface2; + + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + , m_interface2(static_cast(impl)) + {} + + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + , m_interface2(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + InsertInterfaceType(sim, m_interface2); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +template +struct MakeInterfaceMap +{ + ServiceFactory* m_factory; + I1* m_interface1; + + template + MakeInterfaceMap(Impl* impl) + : m_factory(NULL) + , m_interface1(static_cast(impl)) + {} + + MakeInterfaceMap(ServiceFactory* factory) + : m_factory(factory) + , m_interface1(NULL) + { + if (factory == NULL) + { + throw ServiceException("The service factory argument must not be NULL."); + } + } + + operator InterfaceMap () + { + InterfaceMap sim; + InsertInterfaceType(sim, m_interface1); + + if (m_factory) + { + sim.insert(std::make_pair(std::string("org.cppmicroservices.factory"), + static_cast(m_factory))); + } + + return sim; + } +}; + +template<> +struct MakeInterfaceMap; +/// \endcond + +/** + * @ingroup MicroServices + * + * Extract a service interface pointer from a given InterfaceMap instance. + * + * @param map a InterfaceMap instance. + * @return The service interface pointer for the service interface id of the + * \c I1 interface type or NULL if \c map does not contain an entry + * for the given type. + * + * @see MakeInterfaceMap + */ +template +I1* ExtractInterface(const InterfaceMap& map) +{ + InterfaceMap::const_iterator iter = map.find(us_service_interface_iid()); + if (iter != map.end()) + { + return reinterpret_cast(iter->second); + } + return NULL; +} + +US_END_NAMESPACE + + +#endif // USSERVICEINTERFACE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp b/Core/CppMicroServices/src/service/usServiceListenerEntry.cpp similarity index 98% rename from Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp rename to Core/CppMicroServices/src/service/usServiceListenerEntry.cpp index 9dab41cd6b..6dcb178ba0 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp +++ b/Core/CppMicroServices/src/service/usServiceListenerEntry.cpp @@ -1,150 +1,150 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usServiceListenerEntry_p.h" US_BEGIN_NAMESPACE class ServiceListenerEntryData : public SharedData { public: ServiceListenerEntryData(Module* mc, const ServiceListenerEntry::ServiceListener& l, void* data, const std::string& filter) : mc(mc), listener(l), data(data), bRemoved(false), ldap() { if (!filter.empty()) { ldap = LDAPExpr(filter); } } ~ServiceListenerEntryData() { } Module* const mc; ServiceListenerEntry::ServiceListener listener; void* data; bool bRemoved; LDAPExpr ldap; /** * The elements of "simple" filters are cached, for easy lookup. * * The grammar for simple filters is as follows: * *

    * Simple = '(' attr '=' value ')'
    *        | '(' '|' Simple+ ')'
    * 
* where attr is one of Constants#OBJECTCLASS, * Constants#SERVICE_ID or Constants#SERVICE_PID, and * value must not contain a wildcard character. *

* The index of the vector determines which key the cache is for * (see ServiceListenerState#hashedKeys). For each key, there is * a vector pointing out the values which are accepted by this * ServiceListenerEntry's filter. This cache is maintained to make * it easy to remove this service listener. */ LDAPExpr::LocalCache local_cache; private: // purposely not implemented ServiceListenerEntryData(const ServiceListenerEntryData&); ServiceListenerEntryData& operator=(const ServiceListenerEntryData&); }; ServiceListenerEntry::ServiceListenerEntry(const ServiceListenerEntry& other) : d(other.d) { } ServiceListenerEntry::~ServiceListenerEntry() { } ServiceListenerEntry& ServiceListenerEntry::operator=(const ServiceListenerEntry& other) { d = other.d; return *this; } bool ServiceListenerEntry::operator==(const ServiceListenerEntry& other) const { return ((d->mc == 0 || other.d->mc == 0) || d->mc == other.d->mc) && (d->data == other.d->data) && ServiceListenerCompare()(d->listener, other.d->listener); } bool ServiceListenerEntry::operator<(const ServiceListenerEntry& other) const { return (d->mc == other.d->mc) ? (d->data < other.d->data) : (d->mc < other.d->mc); } void ServiceListenerEntry::SetRemoved(bool removed) const { d->bRemoved = removed; } bool ServiceListenerEntry::IsRemoved() const { return d->bRemoved; } ServiceListenerEntry::ServiceListenerEntry(Module* mc, const ServiceListener& l, void* data, const std::string& filter) : d(new ServiceListenerEntryData(mc, l, data, filter)) { } Module* ServiceListenerEntry::GetModule() const { return d->mc; } std::string ServiceListenerEntry::GetFilter() const { return d->ldap.IsNull() ? std::string() : d->ldap.ToString(); } -LDAPExpr ServiceListenerEntry::GetLDAPExpr() const +const LDAPExpr& ServiceListenerEntry::GetLDAPExpr() const { return d->ldap; } LDAPExpr::LocalCache& ServiceListenerEntry::GetLocalCache() const { return d->local_cache; } void ServiceListenerEntry::CallDelegate(const ServiceEvent& event) const { d->listener(event); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h b/Core/CppMicroServices/src/service/usServiceListenerEntry_p.h similarity index 98% rename from Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h rename to Core/CppMicroServices/src/service/usServiceListenerEntry_p.h index ebcf167272..8bedffe193 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h +++ b/Core/CppMicroServices/src/service/usServiceListenerEntry_p.h @@ -1,97 +1,97 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICELISTENERENTRY_H #define USSERVICELISTENERENTRY_H #include #include #include "usLDAPExpr_p.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4396) #endif US_BEGIN_NAMESPACE class Module; class ServiceListenerEntryData; /** * Data structure for saving service listener info. Contains * the optional service listener filter, in addition to the info * in ListenerEntry. */ class ServiceListenerEntry { public: typedef US_SERVICE_LISTENER_FUNCTOR ServiceListener; ServiceListenerEntry(const ServiceListenerEntry& other); ~ServiceListenerEntry(); ServiceListenerEntry& operator=(const ServiceListenerEntry& other); bool operator==(const ServiceListenerEntry& other) const; bool operator<(const ServiceListenerEntry& other) const; void SetRemoved(bool removed) const; bool IsRemoved() const; ServiceListenerEntry(Module* mc, const ServiceListener& l, void* data, const std::string& filter = ""); Module* GetModule() const; std::string GetFilter() const; - LDAPExpr GetLDAPExpr() const; + const LDAPExpr& GetLDAPExpr() const; LDAPExpr::LocalCache& GetLocalCache() const; void CallDelegate(const ServiceEvent& event) const; private: US_HASH_FUNCTION_FRIEND(ServiceListenerEntry); ExplicitlySharedDataPointer d; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif US_HASH_FUNCTION_NAMESPACE_BEGIN US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceListenerEntry)) return US_HASH_FUNCTION(const US_PREPEND_NAMESPACE(ServiceListenerEntryData)*, arg.d.ConstData()); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END #endif // USSERVICELISTENERENTRY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp b/Core/CppMicroServices/src/service/usServiceListeners.cpp similarity index 95% rename from Core/Code/CppMicroServices/src/service/usServiceListeners.cpp rename to Core/CppMicroServices/src/service/usServiceListeners.cpp index c9036c83db..85df22931b 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp +++ b/Core/CppMicroServices/src/service/usServiceListeners.cpp @@ -1,290 +1,290 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usUtils_p.h" #include "usServiceListeners_p.h" -#include "usServiceReferencePrivate.h" +#include "usServiceReferenceBasePrivate.h" #include "usModule.h" //#include US_BEGIN_NAMESPACE const int ServiceListeners::OBJECTCLASS_IX = 0; const int ServiceListeners::SERVICE_ID_IX = 1; ServiceListeners::ServiceListeners() { hashedServiceKeys.push_back(ServiceConstants::OBJECTCLASS()); hashedServiceKeys.push_back(ServiceConstants::SERVICE_ID()); } void ServiceListeners::AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data, const std::string& filter) { MutexLocker lock(mutex); ServiceListenerEntry sle(mc->GetModule(), listener, data, filter); if (serviceSet.find(sle) != serviceSet.end()) { RemoveServiceListener_unlocked(sle); } serviceSet.insert(sle); CheckSimple(sle); } void ServiceListeners::RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data) { ServiceListenerEntry entryToRemove(mc->GetModule(), listener, data); MutexLocker lock(mutex); RemoveServiceListener_unlocked(entryToRemove); } void ServiceListeners::RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove) { for (ServiceListenerEntries::iterator it = serviceSet.begin(); it != serviceSet.end(); ++it) { if (it->operator ==(entryToRemove)) { it->SetRemoved(true); RemoveFromCache(*it); serviceSet.erase(it); break; } } } void ServiceListeners::AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) { MutexLocker lock(moduleListenerMapMutex); ModuleListenerMap::value_type::second_type& listeners = moduleListenerMap[mc]; if (std::find_if(listeners.begin(), listeners.end(), std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))) == listeners.end()) { listeners.push_back(std::make_pair(listener, data)); } } void ServiceListeners::RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) { MutexLocker lock(moduleListenerMapMutex); moduleListenerMap[mc].remove_if(std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))); } void ServiceListeners::ModuleChanged(const ModuleEvent& evt) { MutexLocker lock(moduleListenerMapMutex); for(ModuleListenerMap::iterator i = moduleListenerMap.begin(); i != moduleListenerMap.end(); ++i) { for(std::list >::iterator j = i->second.begin(); j != i->second.end(); ++j) { (j->first)(evt); } } } void ServiceListeners::RemoveAllListeners(ModuleContext* mc) { { MutexLocker lock(mutex); for (ServiceListenerEntries::iterator it = serviceSet.begin(); it != serviceSet.end(); ) { if (it->GetModule() == mc->GetModule()) { RemoveFromCache(*it); serviceSet.erase(it++); } else { ++it; } } } { MutexLocker lock(moduleListenerMapMutex); moduleListenerMap.erase(mc); } } void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, const ServiceEvent& evt) { ServiceListenerEntries matchBefore; ServiceChanged(receivers, evt, matchBefore); } void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, const ServiceEvent& evt, ServiceListenerEntries& matchBefore) { - ServiceReference sr = evt.GetServiceReference(); int n = 0; for (ServiceListenerEntries::const_iterator l = receivers.begin(); l != receivers.end(); ++l) { if (!matchBefore.empty()) { matchBefore.erase(*l); } if (!l->IsRemoved()) { try { ++n; l->CallDelegate(evt); } catch (...) { US_WARN << "Service listener" #ifdef US_MODULE_SUPPORT_ENABLED << " in " << l->GetModule()->GetName() #endif << " threw an exception!"; } } } //US_DEBUG << "Notified " << n << " listeners"; } -void ServiceListeners::GetMatchingServiceListeners(const ServiceReference& sr, ServiceListenerEntries& set, +void ServiceListeners::GetMatchingServiceListeners(const ServiceReferenceBase& sr, ServiceListenerEntries& set, bool lockProps) { MutexLocker lock(mutex); // Check complicated or empty listener filters int n = 0; for (std::list::const_iterator sse = complicatedListeners.begin(); sse != complicatedListeners.end(); ++sse) { ++n; - if (sse->GetLDAPExpr().IsNull() || - sse->GetLDAPExpr().Evaluate(sr.d->GetProperties(), false)) + const LDAPExpr& ldapExpr = sse->GetLDAPExpr(); + if (ldapExpr.IsNull() || + ldapExpr.Evaluate(sr.d->GetProperties(), false)) { set.insert(*sse); } } //US_DEBUG << "Added " << set.size() << " out of " << n // << " listeners with complicated filters"; // Check the cache - const std::list c(any_cast > + const std::vector c(any_cast > (sr.d->GetProperty(ServiceConstants::OBJECTCLASS(), lockProps))); - for (std::list::const_iterator objClass = c.begin(); + for (std::vector::const_iterator objClass = c.begin(); objClass != c.end(); ++objClass) { AddToSet(set, OBJECTCLASS_IX, *objClass); } long service_id = any_cast(sr.d->GetProperty(ServiceConstants::SERVICE_ID(), lockProps)); std::stringstream ss; ss << service_id; AddToSet(set, SERVICE_ID_IX, ss.str()); } void ServiceListeners::RemoveFromCache(const ServiceListenerEntry& sle) { if (!sle.GetLocalCache().empty()) { for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { CacheType& keymap = cache[i]; std::vector& l = sle.GetLocalCache()[i]; for (std::vector::const_iterator it = l.begin(); it != l.end(); ++it) { std::list& sles = keymap[*it]; sles.remove(sle); if (sles.empty()) { keymap.erase(*it); } } } } else { complicatedListeners.remove(sle); } } void ServiceListeners::CheckSimple(const ServiceListenerEntry& sle) { if (sle.GetLDAPExpr().IsNull()) { complicatedListeners.push_back(sle); } else { LDAPExpr::LocalCache local_cache; if (sle.GetLDAPExpr().IsSimple(hashedServiceKeys, local_cache, false)) { sle.GetLocalCache() = local_cache; for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { for (std::vector::const_iterator it = local_cache[i].begin(); it != local_cache[i].end(); ++it) { std::list& sles = cache[i][*it]; sles.push_back(sle); } } } else { //US_DEBUG << "Too complicated filter: " << sle.GetFilter(); complicatedListeners.push_back(sle); } } } void ServiceListeners::AddToSet(ServiceListenerEntries& set, int cache_ix, const std::string& val) { std::list& l = cache[cache_ix][val]; if (!l.empty()) { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches " << l.size(); for (std::list::const_iterator entry = l.begin(); entry != l.end(); ++entry) { set.insert(*entry); } } else { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches none"; } } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceListeners_p.h b/Core/CppMicroServices/src/service/usServiceListeners_p.h similarity index 98% rename from Core/Code/CppMicroServices/src/service/usServiceListeners_p.h rename to Core/CppMicroServices/src/service/usServiceListeners_p.h index 771f45bc0c..0544b58ee3 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceListeners_p.h +++ b/Core/CppMicroServices/src/service/usServiceListeners_p.h @@ -1,176 +1,176 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICELISTENERS_H #define USSERVICELISTENERS_H #include #include #include #include #include "usServiceListenerEntry_p.h" US_BEGIN_NAMESPACE class CoreModuleContext; class ModuleContext; /** * Here we handle all listeners that modules have registered. * */ class ServiceListeners { private: typedef Mutex MutexType; typedef MutexLock MutexLocker; public: typedef US_MODULE_LISTENER_FUNCTOR ModuleListener; typedef US_UNORDERED_MAP_TYPE > > ModuleListenerMap; ModuleListenerMap moduleListenerMap; MutexType moduleListenerMapMutex; typedef US_UNORDERED_MAP_TYPE > CacheType; typedef US_UNORDERED_SET_TYPE ServiceListenerEntries; private: std::vector hashedServiceKeys; static const int OBJECTCLASS_IX; // = 0; static const int SERVICE_ID_IX; // = 1; /* Service listeners with complicated or empty filters */ std::list complicatedListeners; /* Service listeners with "simple" filters are cached. */ CacheType cache[2]; ServiceListenerEntries serviceSet; MutexType mutex; public: ServiceListeners(); /** * Add a new service listener. If an old one exists, and it has the * same owning module, the old listener is removed first. * * @param mc The module context adding this listener. * @param listener The service listener to add. * @param data Additional data to distinguish ServiceListener objects. * @param filter An LDAP filter string to check when a service is modified. * @exception org.osgi.framework.InvalidSyntaxException * If the filter is not a correct LDAP expression. */ void AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data, const std::string& filter); /** * Remove service listener from current framework. Silently ignore * if listener doesn't exist. If listener is registered more than * once remove all instances. * * @param mc The module context who wants to remove listener. * @param listener Object to remove. * @param data Additional data to distinguish ServiceListener objects. */ void RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data); /** * Add a new module listener. * * @param mc The module context adding this listener. * @param listener The module listener to add. * @param data Additional data to distinguish ModuleListener objects. */ void AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data); /** * Remove module listener from current framework. Silently ignore * if listener doesn't exist. * * @param mc The module context who wants to remove listener. * @param listener Object to remove. * @param data Additional data to distinguish ModuleListener objects. */ void RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data); void ModuleChanged(const ModuleEvent& evt); /** * Remove all listener registered by a module in the current framework. * * @param mc Module context which listeners we want to remove. */ void RemoveAllListeners(ModuleContext* mc); /** * Receive notification that a service has had a change occur in its lifecycle. * * @see org.osgi.framework.ServiceListener#serviceChanged */ void ServiceChanged(const ServiceListenerEntries& receivers, const ServiceEvent& evt, ServiceListenerEntries& matchBefore); void ServiceChanged(const ServiceListenerEntries& receivers, const ServiceEvent& evt); /** * * */ - void GetMatchingServiceListeners(const ServiceReference& sr, ServiceListenerEntries& listeners, + void GetMatchingServiceListeners(const ServiceReferenceBase& sr, ServiceListenerEntries& listeners, bool lockProps = true); private: void RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove); /** * Remove all references to a service listener from the service listener * cache. */ void RemoveFromCache(const ServiceListenerEntry& sle); /** * Checks if the specified service listener's filter is simple enough * to cache. */ void CheckSimple(const ServiceListenerEntry& sle); void AddToSet(ServiceListenerEntries& set, int cache_ix, const std::string& val); }; US_END_NAMESPACE #endif // USSERVICELISTENERS_H diff --git a/Core/CppMicroServices/src/service/usServiceObjects.cpp b/Core/CppMicroServices/src/service/usServiceObjects.cpp new file mode 100644 index 0000000000..1595ec283d --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceObjects.cpp @@ -0,0 +1,209 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServiceObjects.h" + +#include "usServiceReferenceBasePrivate.h" + +#include + +US_BEGIN_NAMESPACE + +class ServiceObjectsBasePrivate +{ +public: + + AtomicInt ref; + + ModuleContext* m_context; + ServiceReferenceBase m_reference; + + // This is used by all ServiceObjects instances with S != void + std::map m_serviceInstances; + // This is used by ServiceObjects + std::set m_serviceInterfaceMaps; + + ServiceObjectsBasePrivate(ModuleContext* context, const ServiceReferenceBase& reference) + : m_context(context) + , m_reference(reference) + {} + + InterfaceMap GetServiceInterfaceMap() + { + InterfaceMap result; + + bool isPrototypeScope = m_reference.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == + ServiceConstants::SCOPE_PROTOTYPE(); + + if (isPrototypeScope) + { + result = m_reference.d->GetPrototypeService(m_context->GetModule()); + } + else + { + result = m_reference.d->GetServiceInterfaceMap(m_context->GetModule()); + } + + return result; + } +}; + +ServiceObjectsBase::ServiceObjectsBase(ModuleContext* context, const ServiceReferenceBase& reference) + : d(new ServiceObjectsBasePrivate(context, reference)) +{ + if (!reference) + { + delete d; + throw std::invalid_argument("The service reference is invalid"); + } +} + +void* ServiceObjectsBase::GetService() const +{ + if (!d->m_reference) + { + return NULL; + } + + InterfaceMap im = d->GetServiceInterfaceMap(); + void* result = im.find(d->m_reference.GetInterfaceId())->second; + + if (result) + { + d->m_serviceInstances.insert(std::make_pair(result, im)); + } + return result; +} + +InterfaceMap ServiceObjectsBase::GetServiceInterfaceMap() const +{ + InterfaceMap result; + if (!d->m_reference) + { + return result; + } + + result = d->GetServiceInterfaceMap(); + + if (!result.empty()) + { + d->m_serviceInterfaceMaps.insert(result); + } + return result; +} + +void ServiceObjectsBase::UngetService(void* service) +{ + if (service == NULL) + { + return; + } + + std::map::iterator serviceIter = d->m_serviceInstances.find(service); + if (serviceIter == d->m_serviceInstances.end()) + { + throw std::invalid_argument("The provided service has not been retrieved via this ServiceObjects instance"); + } + + if (!d->m_reference.d->UngetPrototypeService(d->m_context->GetModule(), serviceIter->second)) + { + US_WARN << "Ungetting service unsuccessful"; + } + else + { + d->m_serviceInstances.erase(serviceIter); + } +} + +void ServiceObjectsBase::UngetService(const InterfaceMap& interfaceMap) +{ + if (interfaceMap.empty()) + { + return; + } + + std::set::iterator serviceIter = d->m_serviceInterfaceMaps.find(interfaceMap); + if (serviceIter == d->m_serviceInterfaceMaps.end()) + { + throw std::invalid_argument("The provided service has not been retrieved via this ServiceObjects instance"); + } + + if (!d->m_reference.d->UngetPrototypeService(d->m_context->GetModule(), interfaceMap)) + { + US_WARN << "Ungetting service unsuccessful"; + } + else + { + d->m_serviceInterfaceMaps.erase(serviceIter); + } +} + +ServiceReferenceBase ServiceObjectsBase::GetReference() const +{ + return d->m_reference; +} + +ServiceObjectsBase::ServiceObjectsBase(const ServiceObjectsBase& other) + : d(other.d) +{ + d->ref.Ref(); +} + +ServiceObjectsBase::~ServiceObjectsBase() +{ + if (!d->ref.Deref()) + { + delete d; + } +} + +ServiceObjectsBase& ServiceObjectsBase::operator =(const ServiceObjectsBase& other) +{ + ServiceObjectsBasePrivate* curr_d = d; + d = other.d; + d->ref.Ref(); + + if (!curr_d->ref.Deref()) + delete curr_d; + + return *this; +} + +InterfaceMap ServiceObjects::GetService() const +{ + return this->ServiceObjectsBase::GetServiceInterfaceMap(); +} + +void ServiceObjects::UngetService(const InterfaceMap& service) +{ + this->ServiceObjectsBase::UngetService(service); +} + +ServiceReferenceU ServiceObjects::GetServiceReference() const +{ + return this->ServiceObjectsBase::GetReference(); +} + +ServiceObjects::ServiceObjects(ModuleContext* context, const ServiceReferenceU& reference) + : ServiceObjectsBase(context, reference) +{} + +US_END_NAMESPACE diff --git a/Core/CppMicroServices/src/service/usServiceObjects.h b/Core/CppMicroServices/src/service/usServiceObjects.h new file mode 100644 index 0000000000..f0db27accd --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceObjects.h @@ -0,0 +1,259 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEOBJECTS_H +#define USSERVICEOBJECTS_H + +#include + +#include +#include +#include +#include + +US_BEGIN_NAMESPACE + +class ServiceObjectsBasePrivate; + +class US_EXPORT ServiceObjectsBase +{ + +private: + + ServiceObjectsBasePrivate* d; + +protected: + + ServiceObjectsBase(ModuleContext* context, const ServiceReferenceBase& reference); + + ServiceObjectsBase(const ServiceObjectsBase& other); + + ~ServiceObjectsBase(); + + ServiceObjectsBase& operator=(const ServiceObjectsBase& other); + + // Called by ServiceObjects with S != void + void* GetService() const; + + // Called by the ServiceObjects specialization + InterfaceMap GetServiceInterfaceMap() const; + + // Called by ServiceObjects with S != void + void UngetService(void* service); + + // Called by the ServiceObjects specialization + void UngetService(const InterfaceMap& interfaceMap); + + ServiceReferenceBase GetReference() const; + +}; + +/** + * @ingroup MicroServices + * + * Allows multiple service objects for a service to be obtained. + * + * For services with \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink scope, + * multiple service objects for the service can be obtained. For services with + * \link ServiceConstants::SCOPE_SINGLETON singleton\endlink or + * \link ServiceConstants::SCOPE_MODULE module \endlink scope, only one, use-counted + * service object is available. Any unreleased service objects obtained from this + * ServiceObjects object are automatically released by the framework when the modules + * associated with the ModuleContext used to create this ServiceObjects object is + * stopped. + * + * @tparam S Type of Service. + */ +template +class ServiceObjects : private ServiceObjectsBase +{ + +public: + + /** + * Returns a service object for the referenced service. + * + * This ServiceObjects object can be used to obtain multiple service objects for + * the referenced service if the service has \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink + * scope. If the referenced service has \link ServiceConstants::SCOPE_SINGLETON singleton\endlink + * or \link ServiceConstants::SCOPE_MODULE module\endlink scope, this method + * behaves the same as calling the ModuleContext::GetService(const ServiceReferenceBase&) + * method for the referenced service. That is, only one, use-counted service object + * is available from this ServiceObjects object. + * + * This method will always return \c NULL when the referenced service has been unregistered. + * + * For a prototype scope service, the following steps are taken to get the service object: + * + *

    + *
  1. If the referenced service has been unregistered, \c NULL is returned.
  2. + *
  3. The PrototypeServiceFactory::GetService(Module*, const ServiceRegistrationBase&) + * method is called to create a service object for the caller.
  4. + *
  5. If the service object (an instance of InterfaceMap) returned by the + * PrototypeServiceFactory object is empty, does not contain all the interfaces + * named when the service was registered or the PrototypeServiceFactory object + * throws an exception, \c NULL is returned and a warning message is issued.
  6. + *
  7. The service object is returned.
  8. + *
+ * + * @return A service object for the referenced service or \c NULL if the service is not + * registered, the service object returned by a ServiceFactory does not contain + * all the classes under which it was registered or the ServiceFactory threw an + * exception. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects object + * is no longer valid. + * + * @see UngetService() + */ + S* GetService() const + { + return reinterpret_cast(this->ServiceObjectsBase::GetService()); + } + + /** + * Releases a service object for the referenced service. + * + * This ServiceObjects object can be used to obtain multiple service objects for + * the referenced service if the service has \link ServiceConstants::SCOPE_PROTOTYPE prototype\endlink + * scope. If the referenced service has \link ServiceConstants::SCOPE_SINGLETON singleton\endlink + * or \link ServiceConstants::SCOPE_MODULE module\endlink scope, this method + * behaves the same as calling the ModuleContext::UngetService(const ServiceReferenceBase&) + * method for the referenced service. That is, only one, use-counted service object + * is available from this ServiceObjects object. + * + * For a prototype scope service, the following steps are take to release the service object: + * + *
    + *
  1. If the referenced service has been unregistered, this method returns without + * doing anything.
  2. + *
  3. The PrototypeServiceFactory::UngetService(Module*, const ServiceRegistrationBase&, const InterfaceMap&) + * method is called to release the specified service object.
  4. + *
  5. The specified service object must no longer be used and all references to it + * should be destroyed after calling this method.
  6. + *
+ * + * @param service A service object previously provided by this ServiceObjects object. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects + * object is no longer valid. + * @throw std::invalid_argument If the specified service was not provided by this + * ServiceObjects object. + * + * @see GetService() + */ + void UngetService(S* service) + { + this->ServiceObjectsBase::UngetService(service); + } + + /** + * Returns the ServiceReference for this ServiceObjects object. + * + * @return The ServiceReference for this ServiceObjects object. + */ + ServiceReference GetServiceReference() const + { + return this->ServiceObjectsBase::GetReference(); + } + +private: + + friend class ModuleContext; + + ServiceObjects(ModuleContext* context, const ServiceReference& reference) + : ServiceObjectsBase(context, reference) + {} + +}; + +/** + * @ingroup MicroServices + * + * Allows multiple service objects for a service to be obtained. + * + * This is a specialization of the ServiceObjects class template for + * "void", which maps to all service interface types. + * + * @see ServiceObjects + */ +template<> +class US_EXPORT ServiceObjects : private ServiceObjectsBase +{ + +public: + + /** + * Returns a service object as a InterfaceMap instance for the referenced service. + * + * This method is the same as ServiceObjects::GetService() except for the + * return type. Further, this method will always return an empty InterfaeMap + * object when the referenced service has been unregistered. + * + * @return A InterfaceMap object for the referenced service, which is empty if the + * service is not registered, the InterfaceMap returned by a ServiceFactory + * does not contain all the classes under which the service object was + * registered or the ServiceFactory threw an exception. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects object + * is no longer valid. + * + * @see ServiceObjects::GetService() + * @see UngetService() + */ + InterfaceMap GetService() const; + + /** + * Releases a service object for the referenced service. + * + * This method is the same as ServiceObjects::UngetService() except for the + * parameter type. + * + * @param service An InterfaceMap object previously provided by this ServiceObjects object. + * + * @throw std::logic_error If the ModuleContext used to create this ServiceObjects + * object is no longer valid. + * @throw std::invalid_argument If the specified service was not provided by this + * ServiceObjects object. + * + * @see ServiceObjects::UngetService() + * @see GetService() + */ + void UngetService(const InterfaceMap& service); + + /** + * Returns the ServiceReference for this ServiceObjects object. + * + * @return The ServiceReference for this ServiceObjects object. + */ + ServiceReferenceU GetServiceReference() const; + +private: + + friend class ModuleContext; + + ServiceObjects(ModuleContext* context, const ServiceReferenceU& reference); + +}; + +US_END_NAMESPACE + +#endif // USSERVICEOBJECTS_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceProperties.cpp b/Core/CppMicroServices/src/service/usServiceProperties.cpp similarity index 70% rename from Core/Code/CppMicroServices/src/service/usServiceProperties.cpp rename to Core/CppMicroServices/src/service/usServiceProperties.cpp index 61ee48daf9..d23acc7712 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceProperties.cpp +++ b/Core/CppMicroServices/src/service/usServiceProperties.cpp @@ -1,55 +1,83 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usServiceProperties.h" #include #include US_BEGIN_NAMESPACE const std::string& ServiceConstants::OBJECTCLASS() { static const std::string s("objectclass"); return s; } const std::string& ServiceConstants::SERVICE_ID() { static const std::string s("service.id"); return s; } const std::string& ServiceConstants::SERVICE_RANKING() { static const std::string s("service.ranking"); return s; } +const std::string& ServiceConstants::SERVICE_SCOPE() +{ + static const std::string s("service.scope"); + return s; +} + +const std::string& ServiceConstants::SCOPE_SINGLETON() +{ + static const std::string s("singleton"); + return s; +} + +const std::string& ServiceConstants::SCOPE_MODULE() +{ + static const std::string s("module"); + return s; +} + +const std::string& ServiceConstants::SCOPE_PROTOTYPE() +{ + static const std::string s("prototype"); + return s; +} + US_END_NAMESPACE US_USE_NAMESPACE // make sure all static locals get constructed, so that they // can be used in destructors of global statics. std::string tmp1 = ServiceConstants::OBJECTCLASS(); std::string tmp2 = ServiceConstants::SERVICE_ID(); std::string tmp3 = ServiceConstants::SERVICE_RANKING(); +std::string tmp4 = ServiceConstants::SERVICE_SCOPE(); +std::string tmp5 = ServiceConstants::SCOPE_SINGLETON(); +std::string tmp6 = ServiceConstants::SCOPE_MODULE(); +std::string tmp7 = ServiceConstants::SCOPE_PROTOTYPE(); diff --git a/Core/Code/CppMicroServices/src/service/usServiceProperties.h b/Core/CppMicroServices/src/service/usServiceProperties.h similarity index 55% rename from Core/Code/CppMicroServices/src/service/usServiceProperties.h rename to Core/CppMicroServices/src/service/usServiceProperties.h index a2d4a4a472..208d84ea77 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceProperties.h +++ b/Core/CppMicroServices/src/service/usServiceProperties.h @@ -1,199 +1,138 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef US_SERVICE_PROPERTIES_H #define US_SERVICE_PROPERTIES_H #include #include #include "usAny.h" -/// \cond -US_BEGIN_NAMESPACE - -struct ci_char_traits : public std::char_traits - // just inherit all the other functions - // that we don't need to override -{ - - static bool eq(char c1, char c2) - { - return std::toupper(c1) == std::toupper(c2); - } - - static bool ne(char c1, char c2) - { - return std::toupper(c1) != std::toupper(c2); - } - - static bool lt(char c1, char c2) - { - return std::toupper(c1) < std::toupper(c2); - } - - static bool gt(char c1, char c2) - { - return std::toupper(c1) > std::toupper(c2); - } - - static int compare(const char* s1, const char* s2, std::size_t n) - { - while (n-- > 0) - { - if (lt(*s1, *s2)) return -1; - if (gt(*s1, *s2)) return 1; - ++s1; ++s2; - } - return 0; - } - - static const char* find(const char* s, int n, char a) - { - while (n-- > 0 && std::toupper(*s) != std::toupper(a)) - { - ++s; - } - return s; - } - -}; - -class ci_string : public std::basic_string -{ -private: - - typedef std::basic_string Super; - -public: - - inline ci_string() : Super() {} - inline ci_string(const ci_string& cistr) : Super(cistr) {} - inline ci_string(const ci_string& cistr, size_t pos, size_t n) : Super(cistr, pos, n) {} - inline ci_string(const char* s, size_t n) : Super(s, n) {} - inline ci_string(const char* s) : Super(s) {} - inline ci_string(size_t n, char c) : Super(n, c) {} - - inline ci_string(const std::string& str) : Super(str.begin(), str.end()) {} - - template ci_string(InputIterator b, InputIterator e) - : Super(b, e) - {} - - inline operator std::string () const - { - return std::string(begin(), end()); - } -}; - -US_END_NAMESPACE - -US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ci_string)) - - std::string ls(arg); - std::transform(ls.begin(), ls.end(), ls.begin(), ::tolower); - - using namespace US_HASH_FUNCTION_NAMESPACE; - return US_HASH_FUNCTION(std::string, ls); - -US_HASH_FUNCTION_END -US_HASH_FUNCTION_NAMESPACE_END - -/// \endcond - US_BEGIN_NAMESPACE /** * \ingroup MicroServices * - * A hash table based map class with case-insensitive keys. This class - * uses ci_string as key type and Any as values. Due - * to the conversion capabilities of ci_string, std::string objects - * can be used transparantly to insert or retrieve key-value pairs. - * - *

- * Note that the case of the keys will be preserved. + * A hash table with std::string as the key type and Any as the value + * type. It is typically used for passing service properties to + * ModuleContext::RegisterService. */ -typedef US_UNORDERED_MAP_TYPE ServiceProperties; +typedef US_UNORDERED_MAP_TYPE ServiceProperties; /** * \ingroup MicroServices */ namespace ServiceConstants { /** * Service property identifying all of the class names under which a service * was registered in the framework. The value of this property must be of - * type std::list<std::string>. + * type std::vector<std::string>. * *

* This property is set by the framework when a service is registered. */ US_EXPORT const std::string& OBJECTCLASS(); // = "objectclass" /** * Service property identifying a service's registration number. The value * of this property must be of type long int. * *

* The value of this property is assigned by the framework when a service is * registered. The framework assigns a unique value that is larger than all * previously assigned values since the framework was started. These values * are NOT persistent across restarts of the framework. */ US_EXPORT const std::string& SERVICE_ID(); // = "service.id" /** * Service property identifying a service's ranking number. * *

* This property may be supplied in the * ServiceProperties object passed to the * ModuleContext::RegisterService method. The value of this * property must be of type int. * *

* The service ranking is used by the framework to determine the natural * order of services, see ServiceReference::operator<(const ServiceReference&), * and the default service to be returned from a call to the * {@link ModuleContext::GetServiceReference} method. * *

* The default ranking is zero (0). A service with a ranking of * std::numeric_limits::max() is very likely to be returned as the * default service, whereas a service with a ranking of * std::numeric_limits::min() is very unlikely to be returned. * *

* If the supplied property value is not of type int, it is * deemed to have a ranking value of zero. */ US_EXPORT const std::string& SERVICE_RANKING(); // = "service.ranking" +/** + * Service property identifying a service's scope. + * This property is set by the framework when a service is registered. If the + * registered object implements PrototypeServiceFactory, then the value of this + * service property will be SCOPE_PROTOTYPE(). Otherwise, if the registered + * object implements ServiceFactory, then the value of this service property will + * be SCOPE_MODULE(). Otherwise, the value of this service property will be + * SCOPE_SINGLETON(). + */ +US_EXPORT const std::string& SERVICE_SCOPE(); // = "service.scope" + +/** + * Service scope is singleton. All modules using the service receive the same + * service object. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_SINGLETON(); // = "singleton" + +/** + * Service scope is module. Each module using the service receives a distinct + * service object. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_MODULE(); // = "module" + +/** + * Service scope is prototype. Each module using the service receives either + * a distinct service object or can request multiple distinct service objects + * via ServiceObjects. + * + * @see SERVICE_SCOPE() + */ +US_EXPORT const std::string& SCOPE_PROTOTYPE(); // = "prototype" + } US_END_NAMESPACE #endif // US_SERVICE_PROPERTIES_H diff --git a/Core/CppMicroServices/src/service/usServicePropertiesImpl.cpp b/Core/CppMicroServices/src/service/usServicePropertiesImpl.cpp new file mode 100644 index 0000000000..beca29c558 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServicePropertiesImpl.cpp @@ -0,0 +1,99 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usServicePropertiesImpl_p.h" + +#include +#ifdef US_PLATFORM_WINDOWS +#include +#define ci_compare strnicmp +#else +#include +#define ci_compare strncasecmp +#endif + +US_BEGIN_NAMESPACE + +Any ServicePropertiesImpl::emptyAny; + +ServicePropertiesImpl::ServicePropertiesImpl(const ServiceProperties& p) +{ + keys.reserve(p.size()); + values.reserve(p.size()); + + for (ServiceProperties::const_iterator iter = p.begin(); + iter != p.end(); ++iter) + { + if (Find(iter->first) > -1) + { + std::string msg = "ServiceProperties object contains case variants of the key: "; + msg += iter->first; + throw std::runtime_error(msg.c_str()); + } + keys.push_back(iter->first); + values.push_back(iter->second); + } +} + +const Any& ServicePropertiesImpl::Value(const std::string& key) const +{ + int i = Find(key); + if (i < 0) return emptyAny; + return values[i]; +} + +const Any& ServicePropertiesImpl::Value(int index) const +{ + if (index < 0 || static_cast(index) >= values.size()) + return emptyAny; + return values[index]; +} + +int ServicePropertiesImpl::Find(const std::string& key) const +{ + for (std::size_t i = 0; i < keys.size(); ++i) + { + if (ci_compare(key.c_str(), keys[i].c_str(), key.size()) == 0) + { + return i; + } + } + return -1; +} + +int ServicePropertiesImpl::FindCaseSensitive(const std::string& key) const +{ + for (std::size_t i = 0; i < keys.size(); ++i) + { + if (key == keys[i]) + { + return i; + } + } + return -1; +} + +const std::vector& ServicePropertiesImpl::Keys() const +{ + return keys; +} + +US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usBase.h b/Core/CppMicroServices/src/service/usServicePropertiesImpl_p.h similarity index 61% rename from Core/Code/CppMicroServices/src/util/usBase.h rename to Core/CppMicroServices/src/service/usServicePropertiesImpl_p.h index ba57661d3f..4012d1042e 100644 --- a/Core/Code/CppMicroServices/src/util/usBase.h +++ b/Core/CppMicroServices/src/service/usServicePropertiesImpl_p.h @@ -1,45 +1,55 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ +#ifndef USSERVICEPROPERTIESIMPL_P_H +#define USSERVICEPROPERTIESIMPL_P_H -#ifndef USBASE_H -#define USBASE_H - -#include -#include +#include "usServiceProperties.h" US_BEGIN_NAMESPACE -class Base +class ServicePropertiesImpl { public: - virtual ~Base() {} - virtual const char* GetNameOfClass() const { return "US_PREPEND_NAMESPACE(Base)"; } + explicit ServicePropertiesImpl(const ServiceProperties& props); + + const Any& Value(const std::string& key) const; + const Any& Value(int index) const; + + int Find(const std::string& key) const; + int FindCaseSensitive(const std::string& key) const; + + const std::vector& Keys() const; + +private: + + std::vector keys; + std::vector values; + + static Any emptyAny; + }; US_END_NAMESPACE -template<> inline const char* us_service_impl_name(US_PREPEND_NAMESPACE(Base)* impl) -{ return impl->GetNameOfClass(); } - -#endif // USBASE_H +#endif // USSERVICEPROPERTIESIMPL_P_H diff --git a/Core/CppMicroServices/src/service/usServiceReference.h b/Core/CppMicroServices/src/service/usServiceReference.h new file mode 100644 index 0000000000..ff9bfc6cd0 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceReference.h @@ -0,0 +1,146 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEREFERENCE_H +#define USSERVICEREFERENCE_H + +#include +#include + +//US_MSVC_PUSH_DISABLE_WARNING(4396) + +US_BEGIN_NAMESPACE + +/** + * \ingroup MicroServices + * + * A reference to a service. + * + *

+ * The framework returns ServiceReference objects from the + * ModuleContext::GetServiceReference and + * ModuleContext::GetServiceReferences methods. + *

+ * A ServiceReference object may be shared between modules and + * can be used to examine the properties of the service and to get the service + * object. + *

+ * Every service registered in the framework has a unique + * ServiceRegistration object and may have multiple, distinct + * ServiceReference objects referring to it. + * ServiceReference objects associated with a + * ServiceRegistration are considered equal + * (more specifically, their operator==() + * method will return true when compared). + *

+ * If the same service object is registered multiple times, + * ServiceReference objects associated with different + * ServiceRegistration objects are not equal. + * + * @tparam S The class type of the service interface + * @see ModuleContext::GetServiceReference + * @see ModuleContext::GetServiceReferences + * @see ModuleContext::GetService + * @remarks This class is thread safe. + */ +template +class ServiceReference : public ServiceReferenceBase { + +public: + + typedef S ServiceT; + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReference() : ServiceReferenceBase() + { + } + + ServiceReference(const ServiceReferenceBase& base) + : ServiceReferenceBase(base) + { + const std::string interfaceId(us_service_interface_iid()); + if (GetInterfaceId() != interfaceId) + { + if (this->IsConvertibleTo(interfaceId)) + { + this->SetInterfaceId(interfaceId); + } + else + { + this->operator =(0); + } + } + } + + using ServiceReferenceBase::operator=; + +}; + +/** + * \cond + * + * Specialization for void, representing a generic service + * reference not bound to any interface identifier. + * + */ +template<> +class ServiceReference : public ServiceReferenceBase +{ + +public: + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReference() : ServiceReferenceBase() + { + } + + ServiceReference(const ServiceReferenceBase& base) + : ServiceReferenceBase(base) + { + } + + using ServiceReferenceBase::operator=; + + typedef void ServiceType; +}; +/// \endcond + +/** + * \ingroup MicroServices + * + * A service reference of unknown type, which is not bound to any + * interface identifier. + */ +typedef ServiceReference ServiceReferenceU; + +US_END_NAMESPACE + +//US_MSVC_POP_WARNING + +#endif // USSERVICEREFERENCE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceReference.cpp b/Core/CppMicroServices/src/service/usServiceReferenceBase.cpp similarity index 55% rename from Core/Code/CppMicroServices/src/service/usServiceReference.cpp rename to Core/CppMicroServices/src/service/usServiceReferenceBase.cpp index 68d5c696ec..0ccd9d6559 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReference.cpp +++ b/Core/CppMicroServices/src/service/usServiceReferenceBase.cpp @@ -1,189 +1,201 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#include "usServiceReference.h" -#include "usServiceReferencePrivate.h" -#include "usServiceRegistrationPrivate.h" +#include "usServiceReferenceBase.h" +#include "usServiceReferenceBasePrivate.h" +#include "usServiceRegistrationBasePrivate.h" #include "usModule.h" #include "usModulePrivate.h" US_BEGIN_NAMESPACE -typedef ServiceRegistrationPrivate::MutexType MutexType; +typedef ServiceRegistrationBasePrivate::MutexType MutexType; typedef MutexLock MutexLocker; -ServiceReference::ServiceReference() - : d(new ServiceReferencePrivate(0)) +ServiceReferenceBase::ServiceReferenceBase() + : d(new ServiceReferenceBasePrivate(0)) { } -ServiceReference::ServiceReference(const ServiceReference& ref) +ServiceReferenceBase::ServiceReferenceBase(const ServiceReferenceBase& ref) : d(ref.d) { d->ref.Ref(); } -ServiceReference::ServiceReference(ServiceRegistrationPrivate* reg) - : d(new ServiceReferencePrivate(reg)) +ServiceReferenceBase::ServiceReferenceBase(ServiceRegistrationBasePrivate* reg) + : d(new ServiceReferenceBasePrivate(reg)) { +} +void ServiceReferenceBase::SetInterfaceId(const std::string& interfaceId) +{ + if (d->ref > 1) + { + // detach + d->ref.Deref(); + d = new ServiceReferenceBasePrivate(d->registration); + } + d->interfaceId = interfaceId; } -ServiceReference::operator bool() const +ServiceReferenceBase::operator bool() const { return GetModule() != 0; } -ServiceReference& ServiceReference::operator=(int null) +ServiceReferenceBase& ServiceReferenceBase::operator=(int null) { if (null == 0) { if (!d->ref.Deref()) delete d; - d = new ServiceReferencePrivate(0); + d = new ServiceReferenceBasePrivate(0); } return *this; } -ServiceReference::~ServiceReference() +ServiceReferenceBase::~ServiceReferenceBase() { if (!d->ref.Deref()) delete d; } -Any ServiceReference::GetProperty(const std::string& key) const +Any ServiceReferenceBase::GetProperty(const std::string& key) const { MutexLocker lock(d->registration->propsLock); - ServiceProperties::const_iterator iter = d->registration->properties.find(key); - if (iter != d->registration->properties.end()) - return iter->second; - return Any(); + return d->registration->properties.Value(key); } -void ServiceReference::GetPropertyKeys(std::vector& keys) const +void ServiceReferenceBase::GetPropertyKeys(std::vector& keys) const { MutexLocker lock(d->registration->propsLock); - ServiceProperties::const_iterator iterEnd = d->registration->properties.end(); - for (ServiceProperties::const_iterator iter = d->registration->properties.begin(); - iter != iterEnd; ++iter) - { - keys.push_back(iter->first); - } + const std::vector& ks = d->registration->properties.Keys(); + keys.assign(ks.begin(), ks.end()); } -Module* ServiceReference::GetModule() const +Module* ServiceReferenceBase::GetModule() const { if (d->registration == 0 || d->registration->module == 0) { return 0; } return d->registration->module->q; } -void ServiceReference::GetUsingModules(std::vector& modules) const +void ServiceReferenceBase::GetUsingModules(std::vector& modules) const { MutexLocker lock(d->registration->propsLock); - ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); - for (ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); + ServiceRegistrationBasePrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); + for (ServiceRegistrationBasePrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); iter != end; ++iter) { modules.push_back(iter->first); } } -bool ServiceReference::operator<(const ServiceReference& reference) const +bool ServiceReferenceBase::operator<(const ServiceReferenceBase& reference) const { int r1 = 0; int r2 = 0; Any anyR1 = GetProperty(ServiceConstants::SERVICE_RANKING()); Any anyR2 = reference.GetProperty(ServiceConstants::SERVICE_RANKING()); if (anyR1.Type() == typeid(int)) r1 = any_cast(anyR1); if (anyR2.Type() == typeid(int)) r2 = any_cast(anyR2); if (r1 != r2) { // use ranking if ranking differs return r1 < r2; } else { long int id1 = any_cast(GetProperty(ServiceConstants::SERVICE_ID())); long int id2 = any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())); // otherwise compare using IDs, // is less than if it has a higher ID. return id2 < id1; } } -bool ServiceReference::operator==(const ServiceReference& reference) const +bool ServiceReferenceBase::operator==(const ServiceReferenceBase& reference) const { return d->registration == reference.d->registration; } -ServiceReference& ServiceReference::operator=(const ServiceReference& reference) +ServiceReferenceBase& ServiceReferenceBase::operator=(const ServiceReferenceBase& reference) { - ServiceReferencePrivate* curr_d = d; + ServiceReferenceBasePrivate* curr_d = d; d = reference.d; d->ref.Ref(); if (!curr_d->ref.Deref()) delete curr_d; return *this; } -std::size_t ServiceReference::Hash() const +bool ServiceReferenceBase::IsConvertibleTo(const std::string& interfaceId) const +{ + return d->IsConvertibleTo(interfaceId); +} + +std::string ServiceReferenceBase::GetInterfaceId() const +{ + return d->interfaceId; +} + +std::size_t ServiceReferenceBase::Hash() const { using namespace US_HASH_FUNCTION_NAMESPACE; - return US_HASH_FUNCTION(ServiceRegistrationPrivate*, this->d->registration); + return US_HASH_FUNCTION(ServiceRegistrationBasePrivate*, this->d->registration); } US_END_NAMESPACE US_USE_NAMESPACE -std::ostream& operator<<(std::ostream& os, const ServiceReference& serviceRef) +std::ostream& operator<<(std::ostream& os, const ServiceReferenceBase& serviceRef) { os << "Reference for service object registered from " << serviceRef.GetModule()->GetName() << " " << serviceRef.GetModule()->GetVersion() << " ("; std::vector keys; serviceRef.GetPropertyKeys(keys); size_t keySize = keys.size(); for(size_t i = 0; i < keySize; ++i) { - os << keys[i] << "=" << serviceRef.GetProperty(keys[i]); + os << keys[i] << "=" << serviceRef.GetProperty(keys[i]).ToString(); if (i < keySize-1) os << ","; } os << ")"; return os; } - diff --git a/Core/Code/CppMicroServices/src/service/usServiceReference.h b/Core/CppMicroServices/src/service/usServiceReferenceBase.h similarity index 53% rename from Core/Code/CppMicroServices/src/service/usServiceReference.h rename to Core/CppMicroServices/src/service/usServiceReferenceBase.h index c692f80cb7..9b132920d3 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReference.h +++ b/Core/CppMicroServices/src/service/usServiceReferenceBase.h @@ -1,223 +1,228 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#ifndef USSERVICEREFERENCE_H -#define USSERVICEREFERENCE_H +#ifndef USSERVICEREFERENCEBASE_H +#define USSERVICEREFERENCEBASE_H #include US_MSVC_PUSH_DISABLE_WARNING(4396) US_BEGIN_NAMESPACE class Module; -class ServiceRegistrationPrivate; -class ServiceReferencePrivate; +class ServiceRegistrationBasePrivate; +class ServiceReferenceBasePrivate; /** * \ingroup MicroServices * * A reference to a service. * - *

- * The framework returns ServiceReference objects from the - * ModuleContext::GetServiceReference and - * ModuleContext::GetServiceReferences methods. - *

- * A ServiceReference object may be shared between modules and - * can be used to examine the properties of the service and to get the service - * object. - *

- * Every service registered in the framework has a unique - * ServiceRegistration object and may have multiple, distinct - * ServiceReference objects referring to it. - * ServiceReference objects associated with a - * ServiceRegistration are considered equal - * (more specifically, their operator==() - * method will return true when compared). - *

- * If the same service object is registered multiple times, - * ServiceReference objects associated with different - * ServiceRegistration objects are not equal. - * - * @see ModuleContext::GetServiceReference - * @see ModuleContext::GetServiceReferences - * @see ModuleContext::GetService - * @remarks This class is thread safe. + * \note This class is provided as public API for low-level service queries only. + * In almost all cases you should use the template ServiceReference instead. */ -class US_EXPORT ServiceReference { +class US_EXPORT ServiceReferenceBase { public: - /** - * Creates an invalid ServiceReference object. You can use - * this object in boolean expressions and it will evaluate to - * false. - */ - ServiceReference(); - - ServiceReference(const ServiceReference& ref); + ServiceReferenceBase(const ServiceReferenceBase& ref); /** - * Converts this ServiceReference instance into a boolean + * Converts this ServiceReferenceBase instance into a boolean * expression. If this instance was default constructed or * the service it references has been unregistered, the conversion * returns false, otherwise it returns true. */ operator bool() const; /** * Releases any resources held or locked by this - * ServiceReference and renders it invalid. + * ServiceReferenceBase and renders it invalid. */ - ServiceReference& operator=(int null); + ServiceReferenceBase& operator=(int null); - ~ServiceReference(); + ~ServiceReferenceBase(); /** * Returns the property value to which the specified property key is mapped * in the properties ServiceProperties object of the service - * referenced by this ServiceReference object. + * referenced by this ServiceReferenceBase object. * *

* Property keys are case-insensitive. * *

* This method continues to return property values after the service has * been unregistered. This is so references to unregistered services can * still be interrogated. * * @param key The property key. * @return The property value to which the key is mapped; an invalid Any * if there is no property named after the key. */ Any GetProperty(const std::string& key) const; /** * Returns a list of the keys in the ServiceProperties - * object of the service referenced by this ServiceReference + * object of the service referenced by this ServiceReferenceBase * object. * *

* This method will continue to return the keys after the service has been * unregistered. This is so references to unregistered services can * still be interrogated. * * @param keys A vector being filled with the property keys. */ void GetPropertyKeys(std::vector& keys) const; /** * Returns the module that registered the service referenced by this - * ServiceReference object. + * ServiceReferenceBase object. * *

* This method must return 0 when the service has been * unregistered. This can be used to determine if the service has been * unregistered. * * @return The module that registered the service referenced by this - * ServiceReference object; 0 if that + * ServiceReferenceBase object; 0 if that * service has already been unregistered. - * @see ModuleContext::RegisterService(const std::vector&, US_BASECLASS_NAME*, const ServiceProperties&) + * @see ModuleContext::RegisterService(const InterfaceMap&, const ServiceProperties&) */ Module* GetModule() const; /** * Returns the modules that are using the service referenced by this - * ServiceReference object. Specifically, this method returns + * ServiceReferenceBase object. Specifically, this method returns * the modules whose usage count for that service is greater than zero. * * @param modules A list of modules whose usage count for the service referenced - * by this ServiceReference object is greater than + * by this ServiceReferenceBase object is greater than * zero. */ void GetUsingModules(std::vector& modules) const; /** - * Compares this ServiceReference with the specified - * ServiceReference for order. + * Returns the interface identifier this ServiceReferenceBase object + * is bound to. + * + * A default constructed ServiceReferenceBase object is not bound to + * any interface identifier and calling this method will return an + * empty string. + * + * @return The interface identifier for this ServiceReferenceBase object. + */ + std::string GetInterfaceId() const; + + /** + * Checks wether this ServiceReferenceBase object can be converted to + * another ServiceReferenceBase object, which will be bound to the + * given interface identifier. + * + * ServiceReferenceBase objects can be converted if the underlying service + * implementation was registered under multiple service interfaces. + * + * @param interfaceid + * @return \c true if this ServiceReferenceBase object can be converted, + * \c false otherwise. + */ + bool IsConvertibleTo(const std::string& interfaceid) const; + + /** + * Compares this ServiceReferenceBase with the specified + * ServiceReferenceBase for order. * *

- * If this ServiceReference and the specified - * ServiceReference have the same \link ServiceConstants::SERVICE_ID() - * service id\endlink they are equal. This ServiceReference is less - * than the specified ServiceReference if it has a lower + * If this ServiceReferenceBase and the specified + * ServiceReferenceBase have the same \link ServiceConstants::SERVICE_ID() + * service id\endlink they are equal. This ServiceReferenceBase is less + * than the specified ServiceReferenceBase if it has a lower * {@link ServiceConstants::SERVICE_RANKING service ranking} and greater if it has a - * higher service ranking. Otherwise, if this ServiceReference - * and the specified ServiceReference have the same + * higher service ranking. Otherwise, if this ServiceReferenceBase + * and the specified ServiceReferenceBase have the same * {@link ServiceConstants::SERVICE_RANKING service ranking}, this - * ServiceReference is less than the specified - * ServiceReference if it has a higher + * ServiceReferenceBase is less than the specified + * ServiceReferenceBase if it has a higher * {@link ServiceConstants::SERVICE_ID service id} and greater if it has a lower * service id. * - * @param reference The ServiceReference to be compared. + * @param reference The ServiceReferenceBase to be compared. * @return Returns a false or true if this - * ServiceReference is less than or greater - * than the specified ServiceReference. + * ServiceReferenceBase is less than or greater + * than the specified ServiceReferenceBase. */ - bool operator<(const ServiceReference& reference) const; - - bool operator==(const ServiceReference& reference) const; + bool operator<(const ServiceReferenceBase& reference) const; - ServiceReference& operator=(const ServiceReference& reference); + bool operator==(const ServiceReferenceBase& reference) const; + ServiceReferenceBase& operator=(const ServiceReferenceBase& reference); private: friend class ModulePrivate; friend class ModuleContext; - friend class ServiceFilter; - friend class ServiceRegistrationPrivate; + friend class ServiceObjectsBase; + friend class ServiceObjectsBasePrivate; + friend class ServiceRegistrationBase; + friend class ServiceRegistrationBasePrivate; friend class ServiceListeners; + friend class ServiceRegistry; friend class LDAPFilter; - template friend class ServiceTracker; - template friend class ServiceTrackerPrivate; - template friend class ModuleAbstractTracked; + template friend class ServiceReference; - US_HASH_FUNCTION_FRIEND(ServiceReference); + US_HASH_FUNCTION_FRIEND(ServiceReferenceBase); std::size_t Hash() const; - ServiceReference(ServiceRegistrationPrivate* reg); + /** + * Creates an invalid ServiceReferenceBase object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReferenceBase(); + + ServiceReferenceBase(ServiceRegistrationBasePrivate* reg); + + void SetInterfaceId(const std::string& interfaceId); - ServiceReferencePrivate* d; + ServiceReferenceBasePrivate* d; }; US_END_NAMESPACE US_MSVC_POP_WARNING /** * \ingroup MicroServices */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceReference)& serviceRef); +US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceReferenceBase)& serviceRef); US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceReference)) +US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceReferenceBase)) return arg.Hash(); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END -#endif // USSERVICEREFERENCE_H +#endif // USSERVICEREFERENCEBASE_H diff --git a/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.cpp b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.cpp new file mode 100644 index 0000000000..adce2e1f36 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.cpp @@ -0,0 +1,320 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include + +#include "usServiceReferenceBasePrivate.h" + +#include "usServiceFactory.h" +#include "usServiceException.h" +#include "usServiceRegistry_p.h" +#include "usServiceRegistrationBasePrivate.h" + +#include "usModule.h" +#include "usModulePrivate.h" + +#include + +#include + +US_BEGIN_NAMESPACE + +typedef ServiceRegistrationBasePrivate::MutexLocker MutexLocker; + +ServiceReferenceBasePrivate::ServiceReferenceBasePrivate(ServiceRegistrationBasePrivate* reg) + : ref(1), registration(reg) +{ + if(registration) registration->ref.Ref(); +} + +ServiceReferenceBasePrivate::~ServiceReferenceBasePrivate() +{ + if (registration && !registration->ref.Deref()) + delete registration; +} + +InterfaceMap ServiceReferenceBasePrivate::GetServiceFromFactory(Module* module, + ServiceFactory* factory, + bool isModuleScope) +{ + assert(factory && "Factory service pointer is NULL"); + InterfaceMap s; + try + { + InterfaceMap smap = factory->GetService(module, + ServiceRegistrationBase(registration)); + if (smap.empty()) + { + US_WARN << "ServiceFactory produced null"; + return smap; + } + const std::vector& classes = + ref_any_cast >(registration->properties.Value(ServiceConstants::OBJECTCLASS())); + for (std::vector::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + if (smap.find(*i) == smap.end() && *i != "org.cppmicroservices.factory") + { + US_WARN << "ServiceFactory produced an object " + "that did not implement: " << (*i); + smap.clear(); + return smap; + } + } + s = smap; + + if (isModuleScope) + { + registration->moduleServiceInstance.insert(std::make_pair(module, smap)); + } + else + { + registration->prototypeServiceInstances[module].push_back(smap); + } + } + catch (...) + { + US_WARN << "ServiceFactory threw an exception"; + s.clear(); + } + return s; +} + +InterfaceMap ServiceReferenceBasePrivate::GetPrototypeService(Module* module) +{ + InterfaceMap s; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* factory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + s = GetServiceFromFactory(module, factory, false); + } + } + return s; +} + +void* ServiceReferenceBasePrivate::GetService(Module* module) +{ + void* s = NULL; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* serviceFactory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + + const int count = registration->dependents[module]; + if (count == 0) + { + if (serviceFactory) + { + const InterfaceMap im = GetServiceFromFactory(module, serviceFactory, true); + s = im.find(interfaceId)->second; + } + else + { + s = registration->GetService(interfaceId); + } + } + else + { + if (serviceFactory) + { + // return the already produced instance + s = registration->moduleServiceInstance[module][interfaceId]; + } + else + { + s = registration->GetService(interfaceId); + } + } + + if (s) + { + registration->dependents[module] = count + 1; + } + } + } + return s; +} + +InterfaceMap ServiceReferenceBasePrivate::GetServiceInterfaceMap(Module* module) +{ + InterfaceMap s; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + ServiceFactory* serviceFactory = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + + const int count = registration->dependents[module]; + if (count == 0) + { + if (serviceFactory) + { + s = GetServiceFromFactory(module, serviceFactory, true); + } + else + { + s = registration->service; + } + } + else + { + if (serviceFactory) + { + // return the already produced instance + s = registration->moduleServiceInstance[module]; + } + else + { + s = registration->service; + } + } + + if (!s.empty()) + { + registration->dependents[module] = count + 1; + } + } + } + return s; +} + +bool ServiceReferenceBasePrivate::UngetPrototypeService(Module* module, const InterfaceMap& service) +{ + MutexLocker lock(registration->propsLock); + + ServiceRegistrationBasePrivate::ModuleToServicesMap::iterator iter = + registration->prototypeServiceInstances.find(module); + if (iter == registration->prototypeServiceInstances.end()) + { + return false; + } + + std::list& prototypeServiceMaps = iter->second; + + for (std::list::iterator imIter = prototypeServiceMaps.begin(); + imIter != prototypeServiceMaps.end(); ++imIter) + { + if (service == *imIter) + { + try + { + ServiceFactory* sf = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + sf->UngetService(module, ServiceRegistrationBase(registration), service); + } + catch (const std::exception& /*e*/) + { + US_WARN << "ServiceFactory threw an exception"; + } + prototypeServiceMaps.erase(imIter); + if (prototypeServiceMaps.empty()) + { + registration->prototypeServiceInstances.erase(iter); + } + return true; + } + } + + return false; +} + +bool ServiceReferenceBasePrivate::UngetService(Module* module, bool checkRefCounter) +{ + MutexLocker lock(registration->propsLock); + bool hadReferences = false; + bool removeService = false; + + int count= registration->dependents[module]; + if (count > 0) + { + hadReferences = true; + } + + if(checkRefCounter) + { + if (count > 1) + { + registration->dependents[module] = count - 1; + } + else if(count == 1) + { + removeService = true; + } + } + else + { + removeService = true; + } + + if (removeService) + { + InterfaceMap sfi = registration->moduleServiceInstance[module]; + registration->moduleServiceInstance.erase(module); + if (!sfi.empty()) + { + try + { + ServiceFactory* sf = reinterpret_cast( + registration->GetService("org.cppmicroservices.factory")); + sf->UngetService(module, ServiceRegistrationBase(registration), sfi); + } + catch (const std::exception& /*e*/) + { + US_WARN << "ServiceFactory threw an exception"; + } + } + registration->dependents.erase(module); + } + + return hadReferences; +} + +const ServicePropertiesImpl& ServiceReferenceBasePrivate::GetProperties() const +{ + return registration->properties; +} + +Any ServiceReferenceBasePrivate::GetProperty(const std::string& key, bool lock) const +{ + if (lock) + { + MutexLocker lock(registration->propsLock); + return registration->properties.Value(key); + } + else + { + return registration->properties.Value(key); + } +} + +bool ServiceReferenceBasePrivate::IsConvertibleTo(const std::string& interfaceId) const +{ + return registration->service.find(interfaceId) != registration->service.end(); +} + +US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.h similarity index 61% rename from Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h rename to Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.h index 5dfc241a84..39f9951435 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h +++ b/Core/CppMicroServices/src/service/usServiceReferenceBasePrivate.h @@ -1,118 +1,152 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#ifndef USSERVICEREFERENCEPRIVATE_H -#define USSERVICEREFERENCEPRIVATE_H +#ifndef USSERVICEREFERENCEBASEPRIVATE_H +#define USSERVICEREFERENCEBASEPRIVATE_H #include "usAtomicInt_p.h" -#include "usServiceProperties.h" +#include "usServiceInterface.h" +#include US_BEGIN_NAMESPACE +class Any; class Module; -class ServiceRegistrationPrivate; -class ServiceReferencePrivate; +class ServicePropertiesImpl; +class ServiceRegistrationBasePrivate; +class ServiceReferenceBasePrivate; /** * \ingroup MicroServices */ -class ServiceReferencePrivate +class ServiceReferenceBasePrivate { public: - ServiceReferencePrivate(ServiceRegistrationPrivate* reg); + ServiceReferenceBasePrivate(ServiceRegistrationBasePrivate* reg); - ~ServiceReferencePrivate(); + ~ServiceReferenceBasePrivate(); /** * Get the service object. * * @param module requester of service. * @return Service requested or null in case of failure. */ - US_BASECLASS_NAME* GetService(Module* module); + void* GetService(Module* module); + + InterfaceMap GetServiceInterfaceMap(Module* module); + + /** + * Get new service instance. + * + * @param module requester of service. + * @return Service requested or null in case of failure. + */ + InterfaceMap GetPrototypeService(Module* module); /** * Unget the service object. * * @param module Module who wants remove service. * @param checkRefCounter If true decrement refence counter and remove service * if we reach zero. If false remove service without * checking refence counter. - * @return True if service was remove or false if only refence counter was + * @return True if service was removed or false if only reference counter was * decremented. */ bool UngetService(Module* module, bool checkRefCounter); + /** + * Unget prototype scope service objects. + * + * @param module Module who wants to remove a prototype scope service. + * @param service The prototype scope service pointer. + * @return \c true if the service was removed, \c false otherwise. + */ + bool UngetPrototypeService(Module* module, void* service); + + bool UngetPrototypeService(Module* module, const InterfaceMap& service); + /** * Get all properties registered with this service. * * @return A ServiceProperties object containing properties or being empty * if service has been removed. */ - ServiceProperties GetProperties() const; + const ServicePropertiesImpl& GetProperties() const; /** * Returns the property value to which the specified property key is mapped * in the properties ServiceProperties object of the service * referenced by this ServiceReference object. * *

* Property keys are case-insensitive. * *

* This method must continue to return property values after the service has * been unregistered. This is so references to unregistered services can * still be interrogated. * * @param key The property key. * @param lock If true, access of the properties of the service * referenced by this ServiceReference object will be * synchronized. * @return The property value to which the key is mapped; an invalid Any * if there is no property named after the key. */ Any GetProperty(const std::string& key, bool lock) const; + bool IsConvertibleTo(const std::string& interfaceId) const; + /** * Reference count for implicitly shared private implementation. */ AtomicInt ref; /** * Link to registration object for this reference. */ - ServiceRegistrationPrivate* const registration; + ServiceRegistrationBasePrivate* const registration; + + /** + * The service interface id for this reference. + */ + std::string interfaceId; private: + InterfaceMap GetServiceFromFactory(Module* module, ServiceFactory* factory, + bool isModuleScope); + // purposely not implemented - ServiceReferencePrivate(const ServiceReferencePrivate&); - ServiceReferencePrivate& operator=(const ServiceReferencePrivate&); + ServiceReferenceBasePrivate(const ServiceReferenceBasePrivate&); + ServiceReferenceBasePrivate& operator=(const ServiceReferenceBasePrivate&); }; US_END_NAMESPACE -#endif // USSERVICEREFERENCEPRIVATE_H +#endif // USSERVICEREFERENCEBASEPRIVATE_H diff --git a/Core/CppMicroServices/src/service/usServiceRegistration.h b/Core/CppMicroServices/src/service/usServiceRegistration.h new file mode 100644 index 0000000000..d604ee8a41 --- /dev/null +++ b/Core/CppMicroServices/src/service/usServiceRegistration.h @@ -0,0 +1,203 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSERVICEREGISTRATION_H +#define USSERVICEREGISTRATION_H + +#include "usServiceRegistrationBase.h" + +US_BEGIN_NAMESPACE + +/** + * \ingroup MicroServices + * + * A registered service. + * + *

+ * The framework returns a ServiceRegistration object when a + * ModuleContext#RegisterService() method invocation is successful. + * The ServiceRegistration object is for the private use of the + * registering module and should not be shared with other modules. + *

+ * The ServiceRegistration object may be used to update the + * properties of the service or to unregister the service. + * + * @tparam S Class tyoe of the service interface + * @see ModuleContext#RegisterService() + * @remarks This class is thread safe. + */ +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + /** + * Creates an invalid ServiceRegistration object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ///@{ + /** + * Returns a ServiceReference object for a service being + * registered. + *

+ * The ServiceReference object may be shared with other + * modules. + * + * @throws std::logic_error If this + * ServiceRegistration object has already been + * unregistered or if it is invalid. + * @return ServiceReference object. + */ + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ServiceReference GetReference(InterfaceT) const + { + return this->ServiceRegistrationBase::GetReference(us_service_interface_iid()); + } + ///@} + + using ServiceRegistrationBase::operator=; + + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +/// \cond +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + using ServiceRegistrationBase::operator=; + + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +template +class ServiceRegistration : public ServiceRegistrationBase +{ + +public: + + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceReference GetReference() const + { + return this->GetReference(InterfaceT()); + } + + ServiceReference GetReference(InterfaceT) const + { + return ServiceReference(this->ServiceRegistrationBase::GetReference(us_service_interface_iid())); + } + + using ServiceRegistrationBase::operator=; + +private: + + friend class ModuleContext; + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + +}; + +template<> +class ServiceRegistration : public ServiceRegistrationBase +{ +public: + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistration() : ServiceRegistrationBase() + { + } + + ServiceRegistration(const ServiceRegistrationBase& base) + : ServiceRegistrationBase(base) + { + } + + using ServiceRegistrationBase::operator=; +}; +/// \endcond + +/** + * \ingroup MicroServices + * + * A service registration object of unknown type. + */ +typedef ServiceRegistration ServiceRegistrationU; + +US_END_NAMESPACE + +#endif // USSERVICEREGISTRATION_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp b/Core/CppMicroServices/src/service/usServiceRegistrationBase.cpp similarity index 52% rename from Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp rename to Core/CppMicroServices/src/service/usServiceRegistrationBase.cpp index 6884c9e1c4..b121bb0a60 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBase.cpp @@ -1,247 +1,272 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include -#ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT -#include US_BASECLASS_HEADER -#endif -#include "usServiceRegistration.h" -#include "usServiceRegistrationPrivate.h" +#include "usServiceRegistrationBase.h" +#include "usServiceRegistrationBasePrivate.h" #include "usServiceListenerEntry_p.h" #include "usServiceRegistry_p.h" #include "usServiceFactory.h" #include "usModulePrivate.h" #include "usCoreModuleContext_p.h" #include US_BEGIN_NAMESPACE -typedef ServiceRegistrationPrivate::MutexLocker MutexLocker; +typedef ServiceRegistrationBasePrivate::MutexLocker MutexLocker; -ServiceRegistration::ServiceRegistration() +ServiceRegistrationBase::ServiceRegistrationBase() : d(0) { } -ServiceRegistration::ServiceRegistration(const ServiceRegistration& reg) +ServiceRegistrationBase::ServiceRegistrationBase(const ServiceRegistrationBase& reg) : d(reg.d) { if (d) d->ref.Ref(); } -ServiceRegistration::ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate) +ServiceRegistrationBase::ServiceRegistrationBase(ServiceRegistrationBasePrivate* registrationPrivate) : d(registrationPrivate) { if (d) d->ref.Ref(); } -ServiceRegistration::ServiceRegistration(ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props) - : d(new ServiceRegistrationPrivate(module, service, props)) +ServiceRegistrationBase::ServiceRegistrationBase(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props) + : d(new ServiceRegistrationBasePrivate(module, service, props)) { } -ServiceRegistration::operator bool() const +ServiceRegistrationBase::operator bool() const { return d != 0; } -ServiceRegistration& ServiceRegistration::operator=(int null) +ServiceRegistrationBase& ServiceRegistrationBase::operator=(int null) { if (null == 0) { if (d && !d->ref.Deref()) { delete d; } d = 0; } return *this; } -ServiceRegistration::~ServiceRegistration() +ServiceRegistrationBase::~ServiceRegistrationBase() { if (d && !d->ref.Deref()) delete d; } -ServiceReference ServiceRegistration::GetReference() const +ServiceReferenceBase ServiceRegistrationBase::GetReference(const std::string& interfaceId) const { - if (!d) throw std::logic_error("ServiceRegistration object invalid"); + if (!d) throw std::logic_error("ServiceRegistrationBase object invalid"); if (!d->available) throw std::logic_error("Service is unregistered"); - return d->reference; + ServiceReferenceBase ref = d->reference; + ref.SetInterfaceId(interfaceId); + return ref; } -void ServiceRegistration::SetProperties(const ServiceProperties& props) +void ServiceRegistrationBase::SetProperties(const ServiceProperties& props) { - if (!d) throw std::logic_error("ServiceRegistration object invalid"); + if (!d) throw std::logic_error("ServiceRegistrationBase object invalid"); MutexLocker lock(d->eventLock); ServiceListeners::ServiceListenerEntries before; // TBD, optimize the locking of services { //MutexLocker lock2(d->module->coreCtx->globalFwLock); if (d->available) { // NYI! Optimize the MODIFIED_ENDMATCH code int old_rank = 0; int new_rank = 0; - std::list classes; + std::vector classes; { MutexLocker lock3(d->propsLock); - Any any = d->properties[ServiceConstants::SERVICE_RANKING()]; - if (any.Type() == typeid(int)) old_rank = any_cast(any); + { + const Any& any = d->properties.Value(ServiceConstants::SERVICE_RANKING()); + if (any.Type() == typeid(int)) old_rank = any_cast(any); + } d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, before, false); - classes = ref_any_cast >(d->properties[ServiceConstants::OBJECTCLASS()]); - long int sid = any_cast(d->properties[ServiceConstants::SERVICE_ID()]); - d->properties = ServiceRegistry::CreateServiceProperties(props, classes, sid); + classes = ref_any_cast >(d->properties.Value(ServiceConstants::OBJECTCLASS())); + long int sid = any_cast(d->properties.Value(ServiceConstants::SERVICE_ID())); + d->properties = ServiceRegistry::CreateServiceProperties(props, classes, false, false, sid); - any = d->properties[ServiceConstants::SERVICE_RANKING()]; - if (any.Type() == typeid(int)) new_rank = any_cast(any); + { + const Any& any = d->properties.Value(ServiceConstants::SERVICE_RANKING()); + if (any.Type() == typeid(int)) new_rank = any_cast(any); + } } if (old_rank != new_rank) { d->module->coreCtx->services.UpdateServiceRegistrationOrder(*this, classes); } } else { throw std::logic_error("Service is unregistered"); } } ServiceListeners::ServiceListenerEntries matchingListeners; d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, matchingListeners); d->module->coreCtx->listeners.ServiceChanged(matchingListeners, ServiceEvent(ServiceEvent::MODIFIED, d->reference), before); d->module->coreCtx->listeners.ServiceChanged(before, ServiceEvent(ServiceEvent::MODIFIED_ENDMATCH, d->reference)); } -void ServiceRegistration::Unregister() +void ServiceRegistrationBase::Unregister() { - if (!d) throw std::logic_error("ServiceRegistration object invalid"); + if (!d) throw std::logic_error("ServiceRegistrationBase object invalid"); if (d->unregistering) return; // Silently ignore redundant unregistration. { MutexLocker lock(d->eventLock); if (d->unregistering) return; d->unregistering = true; if (d->available) { if (d->module) { d->module->coreCtx->services.RemoveServiceRegistration(*this); } } else { throw std::logic_error("Service is unregistered"); } } if (d->module) { ServiceListeners::ServiceListenerEntries listeners; d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, listeners); d->module->coreCtx->listeners.ServiceChanged( listeners, ServiceEvent(ServiceEvent::UNREGISTERING, d->reference)); } { MutexLocker lock(d->eventLock); { MutexLocker lock2(d->propsLock); d->available = false; - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - if (d->module) + InterfaceMap::const_iterator factoryIter = d->service.find("org.cppmicroservices.factory"); + if (d->module && factoryIter != d->service.end()) { - ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator end = d->serviceInstances.end(); - for (ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator i = d->serviceInstances.begin(); + ServiceFactory* serviceFactory = reinterpret_cast(factoryIter->second); + ServiceRegistrationBasePrivate::ModuleToServicesMap::const_iterator end = d->prototypeServiceInstances.end(); + + // unget all prototype services + for (ServiceRegistrationBasePrivate::ModuleToServicesMap::const_iterator i = d->prototypeServiceInstances.begin(); i != end; ++i) { - US_BASECLASS_NAME* obj = i->second; + for (std::list::const_iterator listIter = i->second.begin(); + listIter != i->second.end(); ++listIter) + { + const InterfaceMap& service = *listIter; + try + { + // NYI, don't call inside lock + serviceFactory->UngetService(i->first, *this, service); + } + catch (const std::exception& /*ue*/) + { + US_WARN << "ServiceFactory UngetService implementation threw an exception"; + } + } + } + + // unget module scope services + ServiceRegistrationBasePrivate::ModuleToServiceMap::const_iterator moduleEnd = d->moduleServiceInstance.end(); + for (ServiceRegistrationBasePrivate::ModuleToServiceMap::const_iterator i = d->moduleServiceInstance.begin(); + i != moduleEnd; ++i) + { try { // NYI, don't call inside lock - dynamic_cast(d->service)->UngetService(i->first, - *this, - obj); + serviceFactory->UngetService(i->first, *this, i->second); } catch (const std::exception& /*ue*/) { US_WARN << "ServiceFactory UngetService implementation threw an exception"; } } } - #endif d->module = 0; d->dependents.clear(); - d->service = 0; - d->serviceInstances.clear(); + d->service.clear(); + d->prototypeServiceInstances.clear(); + d->moduleServiceInstance.clear(); // increment the reference count, since "d->reference" was used originally // to keep d alive. d->ref.Ref(); d->reference = 0; d->unregistering = false; } } } -bool ServiceRegistration::operator<(const ServiceRegistration& o) const +bool ServiceRegistrationBase::operator<(const ServiceRegistrationBase& o) const { + if ((!d && !o.d) || !o.d) return false; if (!d) return true; return d->reference <(o.d->reference); } -bool ServiceRegistration::operator==(const ServiceRegistration& registration) const +bool ServiceRegistrationBase::operator==(const ServiceRegistrationBase& registration) const { return d == registration.d; } -ServiceRegistration& ServiceRegistration::operator=(const ServiceRegistration& registration) +ServiceRegistrationBase& ServiceRegistrationBase::operator=(const ServiceRegistrationBase& registration) { - ServiceRegistrationPrivate* curr_d = d; + ServiceRegistrationBasePrivate* curr_d = d; d = registration.d; if (d) d->ref.Ref(); if (curr_d && !curr_d->ref.Deref()) delete curr_d; return *this; } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistration.h b/Core/CppMicroServices/src/service/usServiceRegistrationBase.h similarity index 57% rename from Core/Code/CppMicroServices/src/service/usServiceRegistration.h rename to Core/CppMicroServices/src/service/usServiceRegistrationBase.h index 0203adedd2..f4dafda78f 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistration.h +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBase.h @@ -1,191 +1,223 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#ifndef USSERVICEREGISTRATION_H -#define USSERVICEREGISTRATION_H +#ifndef USSERVICEREGISTRATIONBASE_H +#define USSERVICEREGISTRATIONBASE_H #include "usServiceProperties.h" #include "usServiceReference.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4396) #endif US_BEGIN_NAMESPACE class ModulePrivate; +class ServiceRegistrationBasePrivate; +class ServicePropertiesImpl; /** * \ingroup MicroServices * * A registered service. * *

- * The framework returns a ServiceRegistration object when a + * The framework returns a ServiceRegistrationBase object when a * ModuleContext#RegisterService() method invocation is successful. - * The ServiceRegistration object is for the private use of the + * The ServiceRegistrationBase object is for the private use of the * registering module and should not be shared with other modules. *

- * The ServiceRegistration object may be used to update the + * The ServiceRegistrationBase object may be used to update the * properties of the service or to unregister the service. * + * \note This class is provided as public API for low-level service management only. + * In almost all cases you should use the template ServiceRegistration instead. + * * @see ModuleContext#RegisterService() * @remarks This class is thread safe. */ -class US_EXPORT ServiceRegistration { +class US_EXPORT ServiceRegistrationBase { public: + ServiceRegistrationBase(const ServiceRegistrationBase& reg); + /** - * Creates an invalid ServiceRegistration object. You can use - * this object in boolean expressions and it will evaluate to - * false. + * A boolean conversion operator converting this ServiceRegistrationBase object + * to \c true if it is valid and to \c false otherwise. A SeriveRegistration + * object is invalid if it was default-constructed or was invalidated by + * assigning 0 to it. + * + * \see operator=(int) + * + * \return \c true if this ServiceRegistrationBase object is valid, \c false + * otherwise. */ - ServiceRegistration(); - - ServiceRegistration(const ServiceRegistration& reg); - operator bool() const; /** * Releases any resources held or locked by this - * ServiceRegistration and renders it invalid. + * ServiceRegistrationBase and renders it invalid. + * + * \return This ServiceRegistrationBase object. */ - ServiceRegistration& operator=(int null); + ServiceRegistrationBase& operator=(int null); - ~ServiceRegistration(); + ~ServiceRegistrationBase(); /** * Returns a ServiceReference object for a service being * registered. *

* The ServiceReference object may be shared with other * modules. * * @throws std::logic_error If this - * ServiceRegistration object has already been + * ServiceRegistrationBase object has already been * unregistered or if it is invalid. * @return ServiceReference object. */ - ServiceReference GetReference() const; + ServiceReferenceBase GetReference(const std::string& interfaceId = std::string()) const; /** * Updates the properties associated with a service. * *

* The ServiceConstants#OBJECTCLASS and ServiceConstants#SERVICE_ID keys * cannot be modified by this method. These values are set by the framework * when the service is registered in the environment. * *

* The following steps are taken to modify service properties: *

    *
  1. The service's properties are replaced with the provided properties. *
  2. A service event of type ServiceEvent#MODIFIED is fired. *
* * @param properties The properties for this service. See {@link ServiceProperties} * for a list of standard service property keys. Changes should not * be made to this object after calling this method. To update the * service's properties this method should be called again. * - * @throws std::logic_error If this ServiceRegistration + * @throws std::logic_error If this ServiceRegistrationBase * object has already been unregistered or if it is invalid. * @throws std::invalid_argument If properties contains * case variants of the same key name. */ void SetProperties(const ServiceProperties& properties); /** - * Unregisters a service. Remove a ServiceRegistration object - * from the framework service registry. All ServiceRegistration - * objects associated with this ServiceRegistration object + * Unregisters a service. Remove a ServiceRegistrationBase object + * from the framework service registry. All ServiceRegistrationBase + * objects associated with this ServiceRegistrationBase object * can no longer be used to interact with the service once unregistration is * complete. * *

* The following steps are taken to unregister a service: *

    *
  1. The service is removed from the framework service registry so that * it can no longer be obtained. *
  2. A service event of type ServiceEvent#UNREGISTERING is fired * so that modules using this service can release their use of the service. * Once delivery of the service event is complete, the - * ServiceRegistration objects for the service may no longer be + * ServiceRegistrationBase objects for the service may no longer be * used to get a service object for the service. *
  3. For each module whose use count for this service is greater than * zero:
    * The module's use count for this service is set to zero.
    * If the service was registered with a ServiceFactory object, the * ServiceFactory#UngetService method is called to release * the service object for the module. *
* * @throws std::logic_error If this - * ServiceRegistration object has already been + * ServiceRegistrationBase object has already been * unregistered or if it is invalid. * @see ModuleContext#UngetService * @see ServiceFactory#UngetService */ void Unregister(); - bool operator<(const ServiceRegistration& o) const; + /** + * Compare two ServiceRegistrationBase objects. + * + * If both ServiceRegistrationBase objects are valid, the comparison is done + * using the underlying ServiceReference object. Otherwise, this ServiceRegistrationBase + * object is less than the other object if and only if this object is invalid and + * the other object is valid. + * + * @param o The ServiceRegistrationBase object to compare with. + * @return \c true if this ServiceRegistrationBase object is less than the other object. + */ + bool operator<(const ServiceRegistrationBase& o) const; - bool operator==(const ServiceRegistration& registration) const; + bool operator==(const ServiceRegistrationBase& registration) const; - ServiceRegistration& operator=(const ServiceRegistration& registration); + ServiceRegistrationBase& operator=(const ServiceRegistrationBase& registration); private: friend class ServiceRegistry; - friend class ServiceReferencePrivate; - US_HASH_FUNCTION_FRIEND(ServiceRegistration); + friend class ServiceReferenceBasePrivate; + + template friend class ServiceRegistration; + + US_HASH_FUNCTION_FRIEND(ServiceRegistrationBase); + + /** + * Creates an invalid ServiceRegistrationBase object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistrationBase(); - ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate); + ServiceRegistrationBase(ServiceRegistrationBasePrivate* registrationPrivate); - ServiceRegistration(ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props); + ServiceRegistrationBase(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props); - ServiceRegistrationPrivate* d; + ServiceRegistrationBasePrivate* d; }; US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceRegistration)) - return US_HASH_FUNCTION(US_PREPEND_NAMESPACE(ServiceRegistrationPrivate)*, arg.d); +US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceRegistrationBase)) + return US_HASH_FUNCTION(US_PREPEND_NAMESPACE(ServiceRegistrationBasePrivate)*, arg.d); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END -inline std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceRegistration)& /*reg*/) +inline std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceRegistrationBase)& /*reg*/) { - return os << "US_PREPEND_NAMESPACE(ServiceRegistration) object"; + return os << "US_PREPEND_NAMESPACE(ServiceRegistrationBase) object"; } -#endif // USSERVICEREGISTRATION_H +#endif // USSERVICEREGISTRATIONBASE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.cpp similarity index 59% rename from Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp rename to Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.cpp index da050082e1..078ee6fb37 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.cpp @@ -1,60 +1,76 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#include "usServiceRegistrationPrivate.h" +#include "usServiceRegistrationBasePrivate.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4355) #endif US_BEGIN_NAMESPACE -ServiceRegistrationPrivate::ServiceRegistrationPrivate( - ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props) +ServiceRegistrationBasePrivate::ServiceRegistrationBasePrivate( + ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props) : ref(0), service(service), module(module), reference(this), properties(props), available(true), unregistering(false) { // The reference counter is initialized to 0 because it will be // incremented by the "reference" member. } -ServiceRegistrationPrivate::~ServiceRegistrationPrivate() +ServiceRegistrationBasePrivate::~ServiceRegistrationBasePrivate() { } -bool ServiceRegistrationPrivate::IsUsedByModule(Module* p) +bool ServiceRegistrationBasePrivate::IsUsedByModule(Module* p) const { - return dependents.find(p) != dependents.end(); + return (dependents.find(p) != dependents.end()) || + (prototypeServiceInstances.find(p) != prototypeServiceInstances.end()); } -US_BASECLASS_NAME* ServiceRegistrationPrivate::GetService() +const InterfaceMap& ServiceRegistrationBasePrivate::GetInterfaces() const { return service; } +void* ServiceRegistrationBasePrivate::GetService(const std::string& interfaceId) const +{ + if (interfaceId.empty() && service.size() > 0) + { + return service.begin()->second; + } + + InterfaceMap::const_iterator iter = service.find(interfaceId); + if (iter != service.end()) + { + return iter->second; + } + return NULL; +} + US_END_NAMESPACE #ifdef _MSC_VER #pragma warning(pop) #endif diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.h similarity index 62% rename from Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h rename to Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.h index a2099c07f0..504907f61f 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h +++ b/Core/CppMicroServices/src/service/usServiceRegistrationBasePrivate.h @@ -1,143 +1,152 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ -#ifndef USSERVICEREGISTRATIONPRIVATE_H -#define USSERVICEREGISTRATIONPRIVATE_H +#ifndef USSERVICEREGISTRATIONBASEPRIVATE_H +#define USSERVICEREGISTRATIONBASEPRIVATE_H +#include "usServiceInterface.h" #include "usServiceReference.h" -#include "usServiceProperties.h" +#include "usServicePropertiesImpl_p.h" #include "usAtomicInt_p.h" US_BEGIN_NAMESPACE class ModulePrivate; -class ServiceRegistration; +class ServiceRegistrationBase; /** * \ingroup MicroServices */ -class ServiceRegistrationPrivate +class ServiceRegistrationBasePrivate { protected: - friend class ServiceRegistration; + friend class ServiceRegistrationBase; - // The ServiceReferencePrivate class holds a pointer to a - // ServiceRegistrationPrivate instance and needs to manipulate - // its reference count. This way it can keep the ServiceRegistrationPrivate + // The ServiceReferenceBasePrivate class holds a pointer to a + // ServiceRegistrationBasePrivate instance and needs to manipulate + // its reference count. This way it can keep the ServiceRegistrationBasePrivate // instance alive and keep returning service properties for // unregistered service instances. - friend class ServiceReferencePrivate; + friend class ServiceReferenceBasePrivate; /** * Reference count for implicitly shared private implementation. */ AtomicInt ref; /** * Service or ServiceFactory object. */ - US_BASECLASS_NAME* service; + InterfaceMap service; public: typedef Mutex MutexType; typedef MutexLock MutexLocker; typedef US_UNORDERED_MAP_TYPE ModuleToRefsMap; - typedef US_UNORDERED_MAP_TYPE ModuleToServicesMap; + typedef US_UNORDERED_MAP_TYPE ModuleToServiceMap; + typedef US_UNORDERED_MAP_TYPE > ModuleToServicesMap; /** * Modules dependent on this service. Integer is used as * reference counter, counting number of unbalanced getService(). */ ModuleToRefsMap dependents; /** - * Object instances that factory has produced. + * Object instances that a prototype factory has produced. */ - ModuleToServicesMap serviceInstances; + ModuleToServicesMap prototypeServiceInstances; + + /** + * Object instance with module scope that a factory may have produced. + */ + ModuleToServiceMap moduleServiceInstance; /** * Module registering this service. */ ModulePrivate* module; /** * Reference object to this service registration. */ - ServiceReference reference; + ServiceReferenceBase reference; /** * Service properties. */ - ServiceProperties properties; + ServicePropertiesImpl properties; /** * Is service available. I.e., if true then holders * of a ServiceReference for the service are allowed to get it. */ volatile bool available; /** * Avoid recursive unregistrations. I.e., if true then * unregistration of this service has started but is not yet * finished. */ volatile bool unregistering; /** * Lock object for synchronous event delivery. */ MutexType eventLock; // needs to be recursive MutexType propsLock; - ServiceRegistrationPrivate(ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props); + ServiceRegistrationBasePrivate(ModulePrivate* module, const InterfaceMap& service, + const ServicePropertiesImpl& props); - ~ServiceRegistrationPrivate(); + ~ServiceRegistrationBasePrivate(); /** * Check if a module uses this service * * @param p Module to check * @return true if module uses this service */ - bool IsUsedByModule(Module* m); + bool IsUsedByModule(Module* m) const; + + const InterfaceMap& GetInterfaces() const; - US_BASECLASS_NAME* GetService(); + void* GetService(const std::string& interfaceId) const; private: // purposely not implemented - ServiceRegistrationPrivate(const ServiceRegistrationPrivate&); - ServiceRegistrationPrivate& operator=(const ServiceRegistrationPrivate&); + ServiceRegistrationBasePrivate(const ServiceRegistrationBasePrivate&); + ServiceRegistrationBasePrivate& operator=(const ServiceRegistrationBasePrivate&); }; US_END_NAMESPACE -#endif // USSERVICEREGISTRATIONPRIVATE_H +#endif // USSERVICEREGISTRATIONBASEPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp b/Core/CppMicroServices/src/service/usServiceRegistry.cpp similarity index 60% rename from Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp rename to Core/CppMicroServices/src/service/usServiceRegistry.cpp index 5a49cdc7dd..92222eba19 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp +++ b/Core/CppMicroServices/src/service/usServiceRegistry.cpp @@ -1,327 +1,322 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include -#ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT -#include US_BASECLASS_HEADER -#endif - #include "usServiceRegistry_p.h" #include "usServiceFactory.h" +#include "usPrototypeServiceFactory.h" #include "usServiceRegistry_p.h" -#include "usServiceRegistrationPrivate.h" +#include "usServiceRegistrationBasePrivate.h" #include "usModulePrivate.h" #include "usCoreModuleContext_p.h" US_BEGIN_NAMESPACE typedef MutexLock MutexLocker; -ServiceProperties ServiceRegistry::CreateServiceProperties(const ServiceProperties& in, - const std::list& classes, - long sid) +ServicePropertiesImpl ServiceRegistry::CreateServiceProperties(const ServiceProperties& in, + const std::vector& classes, + bool isFactory, bool isPrototypeFactory, + long sid) { static long nextServiceID = 1; ServiceProperties props(in); if (!classes.empty()) { props.insert(std::make_pair(ServiceConstants::OBJECTCLASS(), classes)); } props.insert(std::make_pair(ServiceConstants::SERVICE_ID(), sid != -1 ? sid : nextServiceID++)); - return props; + if (isPrototypeFactory) + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_PROTOTYPE())); + } + else if (isFactory) + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_MODULE())); + } + else + { + props.insert(std::make_pair(ServiceConstants::SERVICE_SCOPE(), ServiceConstants::SCOPE_SINGLETON())); + } + + return ServicePropertiesImpl(props); } ServiceRegistry::ServiceRegistry(CoreModuleContext* coreCtx) : core(coreCtx) { } ServiceRegistry::~ServiceRegistry() { Clear(); } void ServiceRegistry::Clear() { services.clear(); serviceRegistrations.clear(); classServices.clear(); core = 0; } -ServiceRegistration ServiceRegistry::RegisterService(ModulePrivate* module, - const std::list& classes, - US_BASECLASS_NAME* service, +ServiceRegistrationBase ServiceRegistry::RegisterService(ModulePrivate* module, + const InterfaceMap& service, const ServiceProperties& properties) { - if (service == 0) + if (service.empty()) { - throw std::invalid_argument("Can't register 0 as a service"); + throw std::invalid_argument("Can't register empty InterfaceMap as a service"); } + // Check if we got a service factory + bool isFactory = service.count("org.cppmicroservices.factory") > 0; + bool isPrototypeFactory = (isFactory ? dynamic_cast(reinterpret_cast(service.find("org.cppmicroservices.factory")->second)) != NULL : false); + + std::vector classes; // Check if service implements claimed classes and that they exist. - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) + for (InterfaceMap::const_iterator i = service.begin(); + i != service.end(); ++i) { - if (i->empty()) + if (i->first.empty() || (!isFactory && i->second == NULL)) { throw std::invalid_argument("Can't register as null class"); } - - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - if (!(dynamic_cast(service))) - #endif - { - if (!CheckServiceClass(service, *i)) - { - std::string msg; - std::stringstream ss(msg); - ss << "Service class " << us_service_impl_name(service) << " is not an instance of " - << (*i) << ". Maybe you forgot to export the RTTI information for the interface."; - throw std::invalid_argument(msg); - } - } + classes.push_back(i->first); } - ServiceRegistration res(module, service, - CreateServiceProperties(properties, classes)); + ServiceRegistrationBase res(module, service, + CreateServiceProperties(properties, classes, isFactory, isPrototypeFactory)); { MutexLocker lock(mutex); services.insert(std::make_pair(res, classes)); serviceRegistrations.push_back(res); - for (std::list::const_iterator i = classes.begin(); + for (std::vector::const_iterator i = classes.begin(); i != classes.end(); ++i) { - std::list& s = classServices[*i]; - std::list::iterator ip = + std::vector& s = classServices[*i]; + std::vector::iterator ip = std::lower_bound(s.begin(), s.end(), res); s.insert(ip, res); } } - ServiceReference r = res.GetReference(); + ServiceReferenceBase r = res.GetReference(std::string()); ServiceListeners::ServiceListenerEntries listeners; module->coreCtx->listeners.GetMatchingServiceListeners(r, listeners); module->coreCtx->listeners.ServiceChanged(listeners, ServiceEvent(ServiceEvent::REGISTERED, r)); return res; } -void ServiceRegistry::UpdateServiceRegistrationOrder(const ServiceRegistration& sr, - const std::list& classes) +void ServiceRegistry::UpdateServiceRegistrationOrder(const ServiceRegistrationBase& sr, + const std::vector& classes) { MutexLocker lock(mutex); - for (std::list::const_iterator i = classes.begin(); + for (std::vector::const_iterator i = classes.begin(); i != classes.end(); ++i) { - std::list& s = classServices[*i]; + std::vector& s = classServices[*i]; s.erase(std::remove(s.begin(), s.end(), sr), s.end()); s.insert(std::lower_bound(s.begin(), s.end(), sr), sr); } } -bool ServiceRegistry::CheckServiceClass(US_BASECLASS_NAME* , const std::string& ) const -{ - //return service->inherits(cls.toAscii()); - // No possibility to check inheritance based on string literals. - return true; -} - void ServiceRegistry::Get(const std::string& clazz, - std::list& serviceRegs) const + std::vector& serviceRegs) const { MutexLocker lock(mutex); MapClassServices::const_iterator i = classServices.find(clazz); if (i != classServices.end()) { serviceRegs = i->second; } } -ServiceReference ServiceRegistry::Get(ModulePrivate* module, const std::string& clazz) const +ServiceReferenceBase ServiceRegistry::Get(ModulePrivate* module, const std::string& clazz) const { MutexLocker lock(mutex); try { - std::list srs; + std::vector srs; Get_unlocked(clazz, "", module, srs); US_DEBUG << "get service ref " << clazz << " for module " << module->info.name << " = " << srs.size() << " refs"; if (!srs.empty()) { return srs.back(); } } catch (const std::invalid_argument& ) { } - return ServiceReference(); + return ServiceReferenceBase(); } void ServiceRegistry::Get(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& res) const + ModulePrivate* module, std::vector& res) const { MutexLocker lock(mutex); Get_unlocked(clazz, filter, module, res); } void ServiceRegistry::Get_unlocked(const std::string& clazz, const std::string& filter, - ModulePrivate* /*module*/, std::list& res) const + ModulePrivate* /*module*/, std::vector& res) const { - std::list::const_iterator s; - std::list::const_iterator send; - std::list v; + std::vector::const_iterator s; + std::vector::const_iterator send; + std::vector v; LDAPExpr ldap; if (clazz.empty()) { if (!filter.empty()) { ldap = LDAPExpr(filter); LDAPExpr::ObjectClassSet matched; if (ldap.GetMatchedObjectClasses(matched)) { v.clear(); for(LDAPExpr::ObjectClassSet::const_iterator className = matched.begin(); className != matched.end(); ++className) { MapClassServices::const_iterator i = classServices.find(*className); if (i != classServices.end()) { std::copy(i->second.begin(), i->second.end(), std::back_inserter(v)); } } if (!v.empty()) { s = v.begin(); send = v.end(); } else { return; } } else { s = serviceRegistrations.begin(); send = serviceRegistrations.end(); } } else { s = serviceRegistrations.begin(); send = serviceRegistrations.end(); } } else { MapClassServices::const_iterator it = classServices.find(clazz); if (it != classServices.end()) { s = it->second.begin(); send = it->second.end(); } else { return; } if (!filter.empty()) { ldap = LDAPExpr(filter); } } for (; s != send; ++s) { - ServiceReference sri = s->GetReference(); + ServiceReferenceBase sri = s->GetReference(clazz); if (filter.empty() || ldap.Evaluate(s->d->properties, false)) { res.push_back(sri); } } } -void ServiceRegistry::RemoveServiceRegistration(const ServiceRegistration& sr) +void ServiceRegistry::RemoveServiceRegistration(const ServiceRegistrationBase& sr) { MutexLocker lock(mutex); - const std::list& classes = ref_any_cast >( - sr.d->properties[ServiceConstants::OBJECTCLASS()]); + const std::vector& classes = ref_any_cast >( + sr.d->properties.Value(ServiceConstants::OBJECTCLASS())); services.erase(sr); - serviceRegistrations.remove(sr); - for (std::list::const_iterator i = classes.begin(); + serviceRegistrations.erase(std::remove(serviceRegistrations.begin(), serviceRegistrations.end(), sr), + serviceRegistrations.end()); + for (std::vector::const_iterator i = classes.begin(); i != classes.end(); ++i) { - std::list& s = classServices[*i]; + std::vector& s = classServices[*i]; if (s.size() > 1) { s.erase(std::remove(s.begin(), s.end(), sr), s.end()); } else { classServices.erase(*i); } } } void ServiceRegistry::GetRegisteredByModule(ModulePrivate* p, - std::list& res) const + std::vector& res) const { MutexLocker lock(mutex); - for (std::list::const_iterator i = serviceRegistrations.begin(); + for (std::vector::const_iterator i = serviceRegistrations.begin(); i != serviceRegistrations.end(); ++i) { if (i->d->module == p) { res.push_back(*i); } } } void ServiceRegistry::GetUsedByModule(Module* p, - std::list& res) const + std::vector& res) const { MutexLocker lock(mutex); - for (std::list::const_iterator i = serviceRegistrations.begin(); + for (std::vector::const_iterator i = serviceRegistrations.begin(); i != serviceRegistrations.end(); ++i) { if (i->d->IsUsedByModule(p)) { res.push_back(*i); } } } US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h b/Core/CppMicroServices/src/service/usServiceRegistry_p.h similarity index 70% rename from Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h rename to Core/CppMicroServices/src/service/usServiceRegistry_p.h index 49af448db6..9d780ab707 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h +++ b/Core/CppMicroServices/src/service/usServiceRegistry_p.h @@ -1,196 +1,185 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICEREGISTRY_H #define USSERVICEREGISTRY_H -#include - +#include "usServiceInterface.h" #include "usServiceRegistration.h" -#include "usServiceProperties.h" #include "usThreads_p.h" US_BEGIN_NAMESPACE class CoreModuleContext; class ModulePrivate; +class ServicePropertiesImpl; /** * Here we handle all the CppMicroServices services that are registered. */ class ServiceRegistry { public: typedef Mutex MutexType; mutable MutexType mutex; /** * Creates a new ServiceProperties object containing in * with the keys converted to lower case. * * @param classes A list of class names which will be added to the * created ServiceProperties object under the key * ModuleConstants::OBJECTCLASS. * @param sid A service id which will be used instead of a default one. */ - static ServiceProperties CreateServiceProperties(const ServiceProperties& in, - const std::list& classes = std::list(), - long sid = -1); + static ServicePropertiesImpl CreateServiceProperties(const ServiceProperties& in, + const std::vector& classes = std::vector(), + bool isFactory = false, bool isPrototypeFactory = false, long sid = -1); - typedef US_UNORDERED_MAP_TYPE > MapServiceClasses; - typedef US_UNORDERED_MAP_TYPE > MapClassServices; + typedef US_UNORDERED_MAP_TYPE > MapServiceClasses; + typedef US_UNORDERED_MAP_TYPE > MapClassServices; /** * All registered services in the current framework. * Mapping of registered service to class names under which * the service is registerd. */ MapServiceClasses services; - std::list serviceRegistrations; + std::vector serviceRegistrations; /** * Mapping of classname to registered service. * The List of registered services are ordered with the highest * ranked service first. */ MapClassServices classServices; CoreModuleContext* core; ServiceRegistry(CoreModuleContext* coreCtx); ~ServiceRegistry(); void Clear(); /** * Register a service in the framework wide register. * * @param module The module registering the service. * @param classes The class names under which the service can be located. * @param service The service object. * @param properties The properties for this service. * @return A ServiceRegistration object. * @exception std::invalid_argument If one of the following is true: *
    *
  • The service object is 0.
  • *
  • The service parameter is not a ServiceFactory or an * instance of all the named classes in the classes parameter.
  • *
*/ - ServiceRegistration RegisterService(ModulePrivate* module, - const std::list& clazzes, - US_BASECLASS_NAME* service, - const ServiceProperties& properties); + ServiceRegistrationBase RegisterService(ModulePrivate* module, + const InterfaceMap& service, + const ServiceProperties& properties); /** * Service ranking changed, reorder registered services * according to ranking. * * @param serviceRegistration The ServiceRegistrationPrivate object. * @param rank New rank of object. */ - void UpdateServiceRegistrationOrder(const ServiceRegistration& sr, - const std::list& classes); - - /** - * Checks that a given service object is an instance of the given - * class name. - * - * @param service The service object to check. - * @param cls The class name to check for. - */ - bool CheckServiceClass(US_BASECLASS_NAME* service, const std::string& cls) const; + void UpdateServiceRegistrationOrder(const ServiceRegistrationBase& sr, + const std::vector& classes); /** * Get all services implementing a certain class. * Only used internally by the framework. * * @param clazz The class name of the requested service. * @return A sorted list of {@link ServiceRegistrationPrivate} objects. */ - void Get(const std::string& clazz, std::list& serviceRegs) const; + void Get(const std::string& clazz, std::vector& serviceRegs) const; /** * Get a service implementing a certain class. * * @param module The module requesting reference * @param clazz The class name of the requested service. * @return A {@link ServiceReference} object. */ - ServiceReference Get(ModulePrivate* module, const std::string& clazz) const; + ServiceReferenceBase Get(ModulePrivate* module, const std::string& clazz) const; /** * Get all services implementing a certain class and then * filter these with a property filter. * * @param clazz The class name of requested service. * @param filter The property filter. * @param module The module requesting reference. * @return A list of {@link ServiceReference} object. */ void Get(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& serviceRefs) const; + ModulePrivate* module, std::vector& serviceRefs) const; /** * Remove a registered service. * * @param sr The ServiceRegistration object that is registered. */ - void RemoveServiceRegistration(const ServiceRegistration& sr) ; + void RemoveServiceRegistration(const ServiceRegistrationBase& sr) ; /** * Get all services that a module has registered. * * @param p The module * @return A set of {@link ServiceRegistration} objects */ - void GetRegisteredByModule(ModulePrivate* m, std::list& serviceRegs) const; + void GetRegisteredByModule(ModulePrivate* m, std::vector& serviceRegs) const; /** * Get all services that a module uses. * * @param p The module * @return A set of {@link ServiceRegistration} objects */ - void GetUsedByModule(Module* m, std::list& serviceRegs) const; + void GetUsedByModule(Module* m, std::vector& serviceRegs) const; private: void Get_unlocked(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& serviceRefs) const; + ModulePrivate* module, std::vector& serviceRefs) const; // purposely not implemented ServiceRegistry(const ServiceRegistry&); ServiceRegistry& operator=(const ServiceRegistry&); }; US_END_NAMESPACE #endif // USSERVICEREGISTRY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTracker.h b/Core/CppMicroServices/src/service/usServiceTracker.h similarity index 70% rename from Core/Code/CppMicroServices/src/service/usServiceTracker.h rename to Core/CppMicroServices/src/service/usServiceTracker.h index 0915ec51f9..1dee7e7eec 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.h +++ b/Core/CppMicroServices/src/service/usServiceTracker.h @@ -1,433 +1,600 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICETRACKER_H #define USSERVICETRACKER_H #include #include "usServiceReference.h" #include "usServiceTrackerCustomizer.h" #include "usLDAPFilter.h" US_BEGIN_NAMESPACE template class TrackedService; template class ServiceTrackerPrivate; class ModuleContext; +/** + * \ingroup MicroServices + * + * A base class template for type traits for objects tracked by a + * ServiceTracker instance. It provides the \c TrackedType typedef + * and two dummy method definitions. + * + * Tracked type traits (TTT) classes must additionally provide the + * following methods: + * + *
    + *
  • static bool IsValid(const TrackedType& t) Returns \c true if \c t is a valid object, \c false otherwise.
  • + *
  • static void Dispose(TrackedType& t) Clears any resources held by the tracked object \c t.
  • + *
  • static TrackedType DefaultValue() Returns the default value for newly created tracked objects.
  • + *
+ * + * @tparam T The type of the tracked object. + * @tparam TTT The tracked type traits class deriving from this class. + * + * @see ServiceTracker + */ +template +struct TrackedTypeTraitsBase +{ + typedef T TrackedType; + + // Needed for S == void + static TrackedType ConvertToTrackedType(const InterfaceMap&) + { + throw std::runtime_error("A custom ServiceTrackerCustomizer instance is required for custom tracked objects."); + return TTT::DefaultValue(); + } + + // Needed for S != void + static TrackedType ConvertToTrackedType(void*) + { + throw std::runtime_error("A custom ServiceTrackerCustomizer instance is required for custom tracked objects."); + return TTT::DefaultValue(); + } +}; + +/// \cond +template +struct TrackedTypeTraits; +/// \endcond + +/** + * \ingroup MicroServices + * + * Default type traits for custom tracked objects of pointer type. + * + * Use this tracked type traits template for custom tracked objects of + * pointer type with the ServiceTracker class. + * + * @tparam S The type of the service being tracked. + * @tparam T The type of the tracked object. + */ +template +struct TrackedTypeTraits : public TrackedTypeTraitsBase > +{ + typedef T* TrackedType; + + static bool IsValid(const TrackedType& t) + { + return t != NULL; + } + + static TrackedType DefaultValue() + { + return NULL; + } + + static void Dispose(TrackedType& t) + { + t = 0; + } +}; + +/// \cond +template +struct TrackedTypeTraits +{ + typedef S* TrackedType; + + static bool IsValid(const TrackedType& t) + { + return t != NULL; + } + + static TrackedType DefaultValue() + { + return NULL; + } + + static void Dispose(TrackedType& t) + { + t = 0; + } + + static TrackedType ConvertToTrackedType(S* s) + { + return s; + } +}; +/// \endcond + +/// \cond +/* + * This specialization is "special" because the tracked type is not + * void* (as specified in the second template parameter) but InterfaceMap. + * This is in line with the ModuleContext::GetService(...) overloads to + * return either S* or InterfaceMap dependening on the template parameter. + */ +template<> +struct TrackedTypeTraits +{ + typedef InterfaceMap TrackedType; + + static bool IsValid(const TrackedType& t) + { + return !t.empty(); + } + + static TrackedType DefaultValue() + { + return TrackedType(); + } + + static void Dispose(TrackedType& t) + { + t.clear(); + } + + static TrackedType ConvertToTrackedType(const InterfaceMap& im) + { + return im; + } +}; +/// \endcond + /** * \ingroup MicroServices * * The ServiceTracker class simplifies using services from the * framework's service registry. *

* A ServiceTracker object is constructed with search criteria and * a ServiceTrackerCustomizer object. A ServiceTracker * can use a ServiceTrackerCustomizer to customize the service * objects to be tracked. The ServiceTracker can then be opened to * begin tracking all services in the framework's service registry that match * the specified search criteria. The ServiceTracker correctly * handles all of the details of listening to ServiceEvents and * getting and ungetting services. *

* The GetServiceReferences method can be called to get references * to the services being tracked. The GetService and * GetServices methods can be called to get the service objects for * the tracked service. - *

- * The ServiceTracker class is thread-safe. It does not call a - * ServiceTrackerCustomizer while holding any locks. - * ServiceTrackerCustomizer implementations must also be - * thread-safe. * - * \tparam S The type of the service being tracked. The type must be an + * \note The ServiceTracker class is thread-safe. It does not call a + * ServiceTrackerCustomizer while holding any locks. + * ServiceTrackerCustomizer implementations must also be + * thread-safe. + * + * Customization of the services to be tracked requires a custom tracked type traits + * class if the custom tracked type is not a pointer type. To customize a tracked + * service using a custom type with value-semantics like + * \snippet uServices-servicetracker/main.cpp tt + * the custom tracked type traits class should look like this: + * \snippet uServices-servicetracker/main.cpp ttt + * + * For a custom tracked type, a ServiceTrackerCustomizer is required, which knows + * how to associate the tracked service with the custom tracked type: + * \snippet uServices-servicetracker/main.cpp customizer + * The custom tracking type traits class and customizer can now be used to instantiate + * a ServiceTracker: + * \snippet uServices-servicetracker/main.cpp tracker + * + * If the custom tracked type is a pointer type, a suitable tracked type traits + * template is provided by the framework and only a ServiceTrackerCustomizer needs + * to be provided: + * \snippet uServices-servicetracker/main.cpp tracker2 + * + * + * @tparam S The type of the service being tracked. The type S* must be an * assignable datatype. Further, if the - * ServiceTracker(ModuleContext*, ServiceTrackerCustomizer*) + * ServiceTracker(ModuleContext*, ServiceTrackerCustomizer*) * constructor is used, the type must have an associated interface id via * #US_DECLARE_SERVICE_INTERFACE. - * \tparam T The type of the tracked object. The type must be an assignable - * datatype, provide a boolean conversion function, and provide - * a constructor and an assignment operator which can handle 0 as an argument. - * \remarks This class is thread safe. + * @tparam TTT Type traits of the tracked object. The type traits class provides + * information about the customized service object, see TrackedTypeTraitsBase. + * + * @remarks This class is thread safe. */ -template -class ServiceTracker : protected ServiceTrackerCustomizer +template > +class ServiceTracker : protected ServiceTrackerCustomizer { public: - typedef std::map TrackingMap; + /// The type of the service being tracked + typedef S ServiceT; + /// The type of the tracked object + typedef typename TTT::TrackedType T; + + typedef ServiceReference ServiceReferenceT; + + typedef std::map,T> TrackingMap; ~ServiceTracker(); /** * Create a ServiceTracker on the specified * ServiceReference. * *

* The service referenced by the specified ServiceReference * will be tracked by this ServiceTracker. * * @param context The ModuleContext against which the tracking * is done. * @param reference The ServiceReference for the service to be * tracked. * @param customizer The customizer object to call when services are added, * modified, or removed in this ServiceTracker. If * customizer is null, then this * ServiceTracker will be used as the * ServiceTrackerCustomizer and this * ServiceTracker will call the * ServiceTrackerCustomizer methods on itself. */ ServiceTracker(ModuleContext* context, - const ServiceReference& reference, - ServiceTrackerCustomizer* customizer = 0); + const ServiceReferenceT& reference, + ServiceTrackerCustomizer* customizer = 0); /** * Create a ServiceTracker on the specified class name. * *

* Services registered under the specified class name will be tracked by * this ServiceTracker. * * @param context The ModuleContext against which the tracking * is done. * @param clazz The class name of the services to be tracked. * @param customizer The customizer object to call when services are added, * modified, or removed in this ServiceTracker. If * customizer is null, then this * ServiceTracker will be used as the * ServiceTrackerCustomizer and this * ServiceTracker will call the * ServiceTrackerCustomizer methods on itself. */ ServiceTracker(ModuleContext* context, const std::string& clazz, - ServiceTrackerCustomizer* customizer = 0); + ServiceTrackerCustomizer* customizer = 0); /** * Create a ServiceTracker on the specified * LDAPFilter object. * *

* Services which match the specified LDAPFilter object will be * tracked by this ServiceTracker. * * @param context The ModuleContext against which the tracking * is done. * @param filter The LDAPFilter to select the services to be * tracked. * @param customizer The customizer object to call when services are added, * modified, or removed in this ServiceTracker. If * customizer is null, then this ServiceTracker will be * used as the ServiceTrackerCustomizer and this * ServiceTracker will call the * ServiceTrackerCustomizer methods on itself. */ ServiceTracker(ModuleContext* context, const LDAPFilter& filter, - ServiceTrackerCustomizer* customizer = 0); + ServiceTrackerCustomizer* customizer = 0); /** * Create a ServiceTracker on the class template * argument S. * *

* Services registered under the interface name of the class template * argument S will be tracked by this ServiceTracker. * * @param context The ModuleContext against which the tracking * is done. * @param customizer The customizer object to call when services are added, * modified, or removed in this ServiceTracker. If * customizer is null, then this ServiceTracker will be * used as the ServiceTrackerCustomizer and this * ServiceTracker will call the * ServiceTrackerCustomizer methods on itself. */ - ServiceTracker(ModuleContext* context, ServiceTrackerCustomizer* customizer = 0); + ServiceTracker(ModuleContext* context, ServiceTrackerCustomizer* customizer = 0); /** * Open this ServiceTracker and begin tracking services. * *

* Services which match the search criteria specified when this * ServiceTracker was created are now tracked by this * ServiceTracker. * * @throws std::logic_error If the ModuleContext * with which this ServiceTracker was created is no * longer valid. */ virtual void Open(); /** * Close this ServiceTracker. * *

* This method should be called when this ServiceTracker should * end the tracking of services. * *

* This implementation calls GetServiceReferences() to get the list * of tracked services to remove. */ virtual void Close(); /** * Wait for at least one service to be tracked by this * ServiceTracker. This method will also return when this * ServiceTracker is closed. * *

* It is strongly recommended that WaitForService is not used * during the calling of the ModuleActivator methods. * ModuleActivator methods are expected to complete in a short * period of time. * *

* This implementation calls GetService() to determine if a service * is being tracked. * * @return Returns the result of GetService(). */ virtual T WaitForService(unsigned long timeoutMillis = 0); /** * Return a list of ServiceReferences for all services being * tracked by this ServiceTracker. * * @param refs List of ServiceReferences. */ - virtual void GetServiceReferences(std::list& refs) const; + virtual void GetServiceReferences(std::vector& refs) const; /** * Returns a ServiceReference for one of the services being * tracked by this ServiceTracker. * *

* If multiple services are being tracked, the service with the highest * ranking (as specified in its service.ranking property) is * returned. If there is a tie in ranking, the service with the lowest * service ID (as specified in its service.id property); that * is, the service that was registered first is returned. This is the same * algorithm used by ModuleContext::GetServiceReference(). * *

* This implementation calls GetServiceReferences() to get the list * of references for the tracked services. * * @return A ServiceReference for a tracked service. * @throws ServiceException if no services are being tracked. */ - virtual ServiceReference GetServiceReference() const; + virtual ServiceReferenceT GetServiceReference() const; /** * Returns the service object for the specified * ServiceReference if the specified referenced service is * being tracked by this ServiceTracker. * * @param reference The reference to the desired service. * @return A service object or null if the service referenced * by the specified ServiceReference is not being * tracked. */ - virtual T GetService(const ServiceReference& reference) const; + virtual T GetService(const ServiceReferenceT& reference) const; /** * Return a list of service objects for all services being tracked by this * ServiceTracker. * *

* This implementation calls GetServiceReferences() to get the list * of references for the tracked services and then calls * GetService(const ServiceReference&) for each reference to get the * tracked service object. * * @param services A list of service objects or an empty list if no services * are being tracked. */ - virtual void GetServices(std::list& services) const; + virtual void GetServices(std::vector& services) const; /** * Returns a service object for one of the services being tracked by this * ServiceTracker. * *

* If any services are being tracked, this implementation returns the result * of calling %GetService(%GetServiceReference()). * * @return A service object or null if no services are being * tracked. */ virtual T GetService() const; /** * Remove a service from this ServiceTracker. * * The specified service will be removed from this * ServiceTracker. If the specified service was being tracked * then the ServiceTrackerCustomizer::RemovedService method will * be called for that service. * * @param reference The reference to the service to be removed. */ - virtual void Remove(const ServiceReference& reference); + virtual void Remove(const ServiceReferenceT& reference); /** * Return the number of services being tracked by this * ServiceTracker. * * @return The number of services being tracked. */ virtual int Size() const; /** * Returns the tracking count for this ServiceTracker. * * The tracking count is initialized to 0 when this * ServiceTracker is opened. Every time a service is added, * modified or removed from this ServiceTracker, the tracking * count is incremented. * *

* The tracking count can be used to determine if this * ServiceTracker has added, modified or removed a service by * comparing a tracking count value previously collected with the current * tracking count value. If the value has not changed, then no service has * been added, modified or removed from this ServiceTracker * since the previous tracking count was collected. * * @return The tracking count for this ServiceTracker or -1 if * this ServiceTracker is not open. */ virtual int GetTrackingCount() const; /** * Return a sorted map of the ServiceReferences and * service objects for all services being tracked by this * ServiceTracker. The map is sorted in natural order * of ServiceReference. That is, the last entry is the service * with the highest ranking and the lowest service id. * * @param tracked A TrackingMap with the ServiceReferences * and service objects for all services being tracked by this * ServiceTracker. If no services are being tracked, * then the returned map is empty. */ virtual void GetTracked(TrackingMap& tracked) const; /** * Return if this ServiceTracker is empty. * * @return true if this ServiceTracker is not tracking any * services. */ virtual bool IsEmpty() const; protected: /** * Default implementation of the * ServiceTrackerCustomizer::AddingService method. * *

* This method is only called when this ServiceTracker has been * constructed with a null ServiceTrackerCustomizer argument. * *

* This implementation returns the result of calling GetService * on the ModuleContext with which this * ServiceTracker was created passing the specified * ServiceReference. *

* This method can be overridden in a subclass to customize the service * object to be tracked for the service being added. In that case, take care * not to rely on the default implementation of - * \link RemovedService(const ServiceReference&, T service) removedService\endlink + * \link RemovedService(const ServiceReferenceT&, T service) removedService\endlink * to unget the service. * * @param reference The reference to the service being added to this * ServiceTracker. * @return The service object to be tracked for the service added to this * ServiceTracker. * @see ServiceTrackerCustomizer::AddingService(const ServiceReference&) */ - T AddingService(const ServiceReference& reference); + T AddingService(const ServiceReferenceT& reference); /** * Default implementation of the * ServiceTrackerCustomizer::ModifiedService method. * *

* This method is only called when this ServiceTracker has been * constructed with a null ServiceTrackerCustomizer argument. * *

* This implementation does nothing. * * @param reference The reference to modified service. * @param service The service object for the modified service. * @see ServiceTrackerCustomizer::ModifiedService(const ServiceReference&, T) */ - void ModifiedService(const ServiceReference& reference, T service); + void ModifiedService(const ServiceReferenceT& reference, T service); /** * Default implementation of the * ServiceTrackerCustomizer::RemovedService method. * *

* This method is only called when this ServiceTracker has been * constructed with a null ServiceTrackerCustomizer argument. * *

* This implementation calls UngetService, on the * ModuleContext with which this ServiceTracker * was created, passing the specified ServiceReference. *

* This method can be overridden in a subclass. If the default - * implementation of \link AddingService(const ServiceReference&) AddingService\endlink + * implementation of \link AddingService(const ServiceReferenceT&) AddingService\endlink * method was used, this method must unget the service. * * @param reference The reference to removed service. * @param service The service object for the removed service. - * @see ServiceTrackerCustomizer::RemovedService(const ServiceReference&, T) + * @see ServiceTrackerCustomizer::RemovedService(const ServiceReferenceT&, T) */ - void RemovedService(const ServiceReference& reference, T service); + void RemovedService(const ServiceReferenceT& reference, T service); private: - typedef ServiceTracker _ServiceTracker; - typedef TrackedService _TrackedService; - typedef ServiceTrackerPrivate _ServiceTrackerPrivate; - typedef ServiceTrackerCustomizer _ServiceTrackerCustomizer; + typedef ServiceTracker _ServiceTracker; + typedef TrackedService _TrackedService; + typedef ServiceTrackerPrivate _ServiceTrackerPrivate; + typedef ServiceTrackerCustomizer _ServiceTrackerCustomizer; - friend class TrackedService; - friend class ServiceTrackerPrivate; + friend class TrackedService; + friend class ServiceTrackerPrivate; _ServiceTrackerPrivate* const d; }; US_END_NAMESPACE #include "usServiceTracker.tpp" #endif // USSERVICETRACKER_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp b/Core/CppMicroServices/src/service/usServiceTracker.tpp similarity index 64% rename from Core/Code/CppMicroServices/src/service/usServiceTracker.tpp rename to Core/CppMicroServices/src/service/usServiceTracker.tpp index 608c628c61..ea9319d4c1 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp +++ b/Core/CppMicroServices/src/service/usServiceTracker.tpp @@ -1,448 +1,459 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usServiceTrackerPrivate.h" #include "usTrackedService_p.h" #include "usServiceException.h" #include "usModuleContext.h" #include #include US_BEGIN_NAMESPACE -template -ServiceTracker::~ServiceTracker() +template +ServiceTracker::~ServiceTracker() { Close(); delete d; } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4355) #endif -template -ServiceTracker::ServiceTracker(ModuleContext* context, - const ServiceReference& reference, - _ServiceTrackerCustomizer* customizer) +template +ServiceTracker::ServiceTracker(ModuleContext* context, + const ServiceReferenceT& reference, + _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, reference, customizer)) { } -template -ServiceTracker::ServiceTracker(ModuleContext* context, const std::string& clazz, - _ServiceTrackerCustomizer* customizer) +template +ServiceTracker::ServiceTracker(ModuleContext* context, const std::string& clazz, + _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, clazz, customizer)) { } -template -ServiceTracker::ServiceTracker(ModuleContext* context, const LDAPFilter& filter, - _ServiceTrackerCustomizer* customizer) +template +ServiceTracker::ServiceTracker(ModuleContext* context, const LDAPFilter& filter, + _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, filter, customizer)) { } -template -ServiceTracker::ServiceTracker(ModuleContext *context, ServiceTrackerCustomizer *customizer) +template +ServiceTracker::ServiceTracker(ModuleContext *context, _ServiceTrackerCustomizer* customizer) : d(new _ServiceTrackerPrivate(this, context, us_service_interface_iid(), customizer)) { const char* clazz = us_service_interface_iid(); if (clazz == 0) throw ServiceException("The service interface class has no US_DECLARE_SERVICE_INTERFACE macro"); } #ifdef _MSC_VER #pragma warning(pop) #endif -template -void ServiceTracker::Open() +template +void ServiceTracker::Open() { _TrackedService* t; { typename _ServiceTrackerPrivate::Lock l(d); if (d->trackedService) { return; } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::Open: " << d->filter; + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::Open: " << d->filter; t = new _TrackedService(this, d->customizer); { typename _TrackedService::Lock l(*t); try { d->context->AddServiceListener(t, &_TrackedService::ServiceChanged, d->listenerFilter); - std::list references; + std::vector references; if (!d->trackClass.empty()) { references = d->GetInitialReferences(d->trackClass, std::string()); } else { if (d->trackReference.GetModule() != 0) { references.push_back(d->trackReference); } else { /* user supplied filter */ references = d->GetInitialReferences(std::string(), (d->listenerFilter.empty()) ? d->filter.ToString() : d->listenerFilter); } } /* set tracked with the initial references */ t->SetInitial(references); } catch (const std::invalid_argument& e) { throw std::runtime_error(std::string("unexpected std::invalid_argument exception: ") + e.what()); } } d->trackedService = t; } /* Call tracked outside of synchronized region */ t->TrackInitial(); /* process the initial references */ } -template -void ServiceTracker::Close() +template +void ServiceTracker::Close() { _TrackedService* outgoing; - std::list references; + std::vector references; { typename _ServiceTrackerPrivate::Lock l(d); outgoing = d->trackedService; if (outgoing == 0) { return; } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::close:" << d->filter; + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::close:" << d->filter; outgoing->Close(); GetServiceReferences(references); d->trackedService = 0; try { d->context->RemoveServiceListener(outgoing, &_TrackedService::ServiceChanged); } catch (const std::logic_error& /*e*/) { /* In case the context was stopped. */ } } d->Modified(); /* clear the cache */ { typename _TrackedService::Lock l(outgoing); outgoing->NotifyAll(); /* wake up any waiters */ } - for(std::list::const_iterator ref = references.begin(); + for(typename std::vector::const_iterator ref = references.begin(); ref != references.end(); ++ref) { outgoing->Untrack(*ref, ServiceEvent()); } if (d->DEBUG_OUTPUT) { typename _ServiceTrackerPrivate::Lock l(d); - if ((d->cachedReference.GetModule() == 0) && (d->cachedService == 0)) + if ((d->cachedReference.GetModule() == 0) && !TTT::IsValid(d->cachedService)) { - US_DEBUG(true) << "ServiceTracker::close[cached cleared]:" + US_DEBUG(true) << "ServiceTracker::close[cached cleared]:" << d->filter; } } delete outgoing; d->trackedService = 0; } -template -T ServiceTracker::WaitForService(unsigned long timeoutMillis) +template +typename ServiceTracker::T +ServiceTracker::WaitForService(unsigned long timeoutMillis) { T object = GetService(); - while (object == 0) + while (!TTT::IsValid(object)) { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ - return 0; + return TTT::DefaultValue(); } { typename _TrackedService::Lock l(t); if (t->Size() == 0) { t->Wait(timeoutMillis); } } object = GetService(); } return object; } -template -void ServiceTracker::GetServiceReferences(std::list& refs) const +template +void ServiceTracker::GetServiceReferences(std::vector& refs) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } { typename _TrackedService::Lock l(t); d->GetServiceReferences_unlocked(refs, t); } } -template -ServiceReference ServiceTracker::GetServiceReference() const +template +typename ServiceTracker::ServiceReferenceT +ServiceTracker::GetServiceReference() const { - ServiceReference reference(0); + ServiceReferenceT reference; { typename _ServiceTrackerPrivate::Lock l(d); reference = d->cachedReference; } if (reference.GetModule() != 0) { - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference[cached]:" + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference[cached]:" << d->filter; return reference; } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference:" << d->filter; - std::list references; + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference:" << d->filter; + std::vector references; GetServiceReferences(references); std::size_t length = references.size(); if (length == 0) { /* if no service is being tracked */ throw ServiceException("No service is being tracked"); } - std::list::const_iterator selectedRef; + typename std::vector::const_iterator selectedRef = references.begin(); if (length > 1) { /* if more than one service, select highest ranking */ std::vector rankings(length); int count = 0; int maxRanking = std::numeric_limits::min(); - std::list::const_iterator refIter = references.begin(); + typename std::vector::const_iterator refIter = references.begin(); for (std::size_t i = 0; i < length; i++) { Any rankingAny = refIter->GetProperty(ServiceConstants::SERVICE_RANKING()); int ranking = 0; if (rankingAny.Type() == typeid(int)) { ranking = any_cast(rankingAny); } rankings[i] = ranking; if (ranking > maxRanking) { selectedRef = refIter; maxRanking = ranking; count = 1; } else { if (ranking == maxRanking) { count++; } } ++refIter; } if (count > 1) { /* if still more than one service, select lowest id */ long int minId = std::numeric_limits::max(); refIter = references.begin(); for (std::size_t i = 0; i < length; i++) { if (rankings[i] == maxRanking) { Any idAny = refIter->GetProperty(ServiceConstants::SERVICE_ID()); long int id = 0; if (idAny.Type() == typeid(long int)) { id = any_cast(idAny); } if (id < minId) { selectedRef = refIter; minId = id; } } ++refIter; } } } { typename _ServiceTrackerPrivate::Lock l(d); d->cachedReference = *selectedRef; return d->cachedReference; } } -template -T ServiceTracker::GetService(const ServiceReference& reference) const +template +typename ServiceTracker::T +ServiceTracker::GetService(const ServiceReferenceT& reference) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ - return 0; + return TTT::DefaultValue(); } { typename _TrackedService::Lock l(t); return t->GetCustomizedObject(reference); } } -template -void ServiceTracker::GetServices(std::list& services) const +template +void ServiceTracker::GetServices(std::vector& services) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } { typename _TrackedService::Lock l(t); - std::list references; + std::vector references; d->GetServiceReferences_unlocked(references, t); - for(std::list::const_iterator ref = references.begin(); + for(typename std::vector::const_iterator ref = references.begin(); ref != references.end(); ++ref) { services.push_back(t->GetCustomizedObject(*ref)); } } } -template -T ServiceTracker::GetService() const +template +typename ServiceTracker::T +ServiceTracker::GetService() const { - T service = d->cachedService; - if (service != 0) { - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService[cached]:" - << d->filter; - return service; + typename _ServiceTrackerPrivate::Lock l(d); + const T& service = d->cachedService; + if (TTT::IsValid(service)) + { + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService[cached]:" + << d->filter; + return service; + } } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService:" << d->filter; + US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService:" << d->filter; try { - ServiceReference reference = GetServiceReference(); + ServiceReferenceT reference = GetServiceReference(); if (reference.GetModule() == 0) { - return 0; + return TTT::DefaultValue(); + } + { + typename _ServiceTrackerPrivate::Lock l(d); + return d->cachedService = GetService(reference); } - return d->cachedService = GetService(reference); } catch (const ServiceException&) { - return 0; + return TTT::DefaultValue(); } } -template -void ServiceTracker::Remove(const ServiceReference& reference) +template +void ServiceTracker::Remove(const ServiceReferenceT& reference) { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } t->Untrack(reference, ServiceEvent()); } -template -int ServiceTracker::Size() const +template +int ServiceTracker::Size() const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return 0; } { typename _TrackedService::Lock l(t); return static_cast(t->Size()); } } -template -int ServiceTracker::GetTrackingCount() const +template +int ServiceTracker::GetTrackingCount() const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return -1; } { typename _TrackedService::Lock l(t); return t->GetTrackingCount(); } } -template -void ServiceTracker::GetTracked(TrackingMap& map) const +template +void ServiceTracker::GetTracked(TrackingMap& map) const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return; } { typename _TrackedService::Lock l(t); t->CopyEntries(map); } } -template -bool ServiceTracker::IsEmpty() const +template +bool ServiceTracker::IsEmpty() const { _TrackedService* t = d->Tracked(); if (t == 0) { /* if ServiceTracker is not open */ return true; } { typename _TrackedService::Lock l(t); return t->IsEmpty(); } } -template -T ServiceTracker::AddingService(const ServiceReference& reference) +template +typename ServiceTracker::T +ServiceTracker::AddingService(const ServiceReferenceT& reference) { - return dynamic_cast(d->context->GetService(reference)); + return TTT::ConvertToTrackedType(d->context->GetService(reference)); } -template -void ServiceTracker::ModifiedService(const ServiceReference& /*reference*/, T /*service*/) +template +void ServiceTracker::ModifiedService(const ServiceReferenceT& /*reference*/, T /*service*/) { /* do nothing */ } -template -void ServiceTracker::RemovedService(const ServiceReference& reference, T /*service*/) +template +void ServiceTracker::RemovedService(const ServiceReferenceT& reference, T /*service*/) { d->context->UngetService(reference); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h b/Core/CppMicroServices/src/service/usServiceTrackerCustomizer.h similarity index 91% rename from Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h rename to Core/CppMicroServices/src/service/usServiceTrackerCustomizer.h index f3704a7930..f7aa7e0eb1 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h +++ b/Core/CppMicroServices/src/service/usServiceTrackerCustomizer.h @@ -1,113 +1,117 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICETRACKERCUSTOMIZER_H #define USSERVICETRACKERCUSTOMIZER_H #include "usServiceReference.h" US_BEGIN_NAMESPACE /** * \ingroup MicroServices * * The ServiceTrackerCustomizer interface allows a * ServiceTracker to customize the service objects that are * tracked. A ServiceTrackerCustomizer is called when a service is * being added to a ServiceTracker. The * ServiceTrackerCustomizer can then return an object for the * tracked service. A ServiceTrackerCustomizer is also called when * a tracked service is modified or has been removed from a * ServiceTracker. * *

* The methods in this interface may be called as the result of a * ServiceEvent being received by a ServiceTracker. * Since ServiceEvents are synchronously delivered, * it is highly recommended that implementations of these methods do * not register (ModuleContext::RegisterService), modify ( * ServiceRegistration::SetProperties) or unregister ( * ServiceRegistration::Unregister) a service while being * synchronized on any object. * *

* The ServiceTracker class is thread-safe. It does not call a * ServiceTrackerCustomizer while holding any locks. * ServiceTrackerCustomizer implementations must also be * thread-safe. * + * \tparam S The type of the service being tracked * \tparam T The type of the tracked object. * \remarks This class is thread safe. */ -template +template struct ServiceTrackerCustomizer { + typedef S ServiceT; + typedef ServiceReference ServiceReferenceT; + virtual ~ServiceTrackerCustomizer() {} /** * A service is being added to the ServiceTracker. * *

* This method is called before a service which matched the search * parameters of the ServiceTracker is added to the * ServiceTracker. This method should return the service object * to be tracked for the specified ServiceReference. The * returned service object is stored in the ServiceTracker and * is available from the GetService and * GetServices methods. * * @param reference The reference to the service being added to the * ServiceTracker. * @return The service object to be tracked for the specified referenced * service or 0 if the specified referenced service * should not be tracked. */ - virtual T AddingService(const ServiceReference& reference) = 0; + virtual T AddingService(const ServiceReferenceT& reference) = 0; /** * A service tracked by the ServiceTracker has been modified. * *

* This method is called when a service being tracked by the * ServiceTracker has had it properties modified. * * @param reference The reference to the service that has been modified. * @param service The service object for the specified referenced service. */ - virtual void ModifiedService(const ServiceReference& reference, T service) = 0; + virtual void ModifiedService(const ServiceReferenceT& reference, T service) = 0; /** * A service tracked by the ServiceTracker has been removed. * *

* This method is called after a service is no longer being tracked by the * ServiceTracker. * * @param reference The reference to the service that has been removed. * @param service The service object for the specified referenced service. */ - virtual void RemovedService(const ServiceReference& reference, T service) = 0; + virtual void RemovedService(const ServiceReferenceT& reference, T service) = 0; }; US_END_NAMESPACE #endif // USSERVICETRACKERCUSTOMIZER_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h b/Core/CppMicroServices/src/service/usServiceTrackerPrivate.h similarity index 74% rename from Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h rename to Core/CppMicroServices/src/service/usServiceTrackerPrivate.h index 1229b68ca0..0d0d4f3efa 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h +++ b/Core/CppMicroServices/src/service/usServiceTrackerPrivate.h @@ -1,172 +1,172 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USSERVICETRACKERPRIVATE_H #define USSERVICETRACKERPRIVATE_H #include "usServiceReference.h" #include "usLDAPFilter.h" US_BEGIN_NAMESPACE /** * \ingroup MicroServices */ -template -class ServiceTrackerPrivate : US_DEFAULT_THREADING > +template +class ServiceTrackerPrivate : US_DEFAULT_THREADING > { public: - ServiceTrackerPrivate(ServiceTracker* st, + typedef typename TTT::TrackedType T; + + ServiceTrackerPrivate(ServiceTracker* st, ModuleContext* context, - const ServiceReference& reference, - ServiceTrackerCustomizer* customizer); + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer); - ServiceTrackerPrivate(ServiceTracker* st, + ServiceTrackerPrivate(ServiceTracker* st, ModuleContext* context, const std::string& clazz, - ServiceTrackerCustomizer* customizer); + ServiceTrackerCustomizer* customizer); - ServiceTrackerPrivate(ServiceTracker* st, + ServiceTrackerPrivate(ServiceTracker* st, ModuleContext* context, const LDAPFilter& filter, - ServiceTrackerCustomizer* customizer); + ServiceTrackerCustomizer* customizer); ~ServiceTrackerPrivate(); /** * Returns the list of initial ServiceReferences that will be * tracked by this ServiceTracker. * * @param className The class name with which the service was registered, or * null for all services. * @param filterString The filter criteria or null for all * services. * @return The list of initial ServiceReferences. * @throws std::invalid_argument If the specified filterString has an * invalid syntax. */ - std::list GetInitialReferences(const std::string& className, - const std::string& filterString); + std::vector > GetInitialReferences(const std::string& className, + const std::string& filterString); - void GetServiceReferences_unlocked(std::list& refs, TrackedService* t) const; + void GetServiceReferences_unlocked(std::vector >& refs, TrackedService* t) const; /* set this to true to compile in debug messages */ static const bool DEBUG_OUTPUT; // = false; /** * The Module Context used by this ServiceTracker. */ ModuleContext* const context; /** * The filter used by this ServiceTracker which specifies the * search criteria for the services to track. */ LDAPFilter filter; /** * The ServiceTrackerCustomizer for this tracker. */ - ServiceTrackerCustomizer* customizer; + ServiceTrackerCustomizer* customizer; /** * Filter string for use when adding the ServiceListener. If this field is * set, then certain optimizations can be taken since we don't have a user * supplied filter. */ std::string listenerFilter; /** * Class name to be tracked. If this field is set, then we are tracking by * class name. */ std::string trackClass; /** * Reference to be tracked. If this field is set, then we are tracking a * single ServiceReference. */ - ServiceReference trackReference; + ServiceReference trackReference; /** * Tracked services: ServiceReference -> customized Object and * ServiceListenerEntry object */ - TrackedService* trackedService; + TrackedService* trackedService; /** * Accessor method for the current TrackedService object. This method is only * intended to be used by the unsynchronized methods which do not modify the * trackedService field. * * @return The current Tracked object. */ - TrackedService* Tracked() const; + TrackedService* Tracked() const; /** * Called by the TrackedService object whenever the set of tracked services is * modified. Clears the cache. */ /* * This method must not be synchronized since it is called by TrackedService while * TrackedService is synchronized. We don't want synchronization interactions * between the listener thread and the user thread. */ void Modified(); /** * Cached ServiceReference for getServiceReference. */ - mutable ServiceReference cachedReference; + mutable ServiceReference cachedReference; /** * Cached service object for GetService. - * - * This field is volatile since it is accessed by multiple threads. */ - mutable T volatile cachedService; + mutable T cachedService; private: - inline ServiceTracker* q_func() + inline ServiceTracker* q_func() { - return static_cast *>(q_ptr); + return static_cast *>(q_ptr); } - inline const ServiceTracker* q_func() const + inline const ServiceTracker* q_func() const { - return static_cast *>(q_ptr); + return static_cast *>(q_ptr); } - friend class ServiceTracker; + friend class ServiceTracker; - ServiceTracker * const q_ptr; + ServiceTracker * const q_ptr; }; US_END_NAMESPACE #include "usServiceTrackerPrivate.tpp" #endif // USSERVICETRACKERPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp b/Core/CppMicroServices/src/service/usServiceTrackerPrivate.tpp similarity index 59% rename from Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp rename to Core/CppMicroServices/src/service/usServiceTrackerPrivate.tpp index e48033f6a1..e4f7fd6e2b 100644 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp +++ b/Core/CppMicroServices/src/service/usServiceTrackerPrivate.tpp @@ -1,144 +1,155 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usTrackedService_p.h" #include "usModuleContext.h" #include "usLDAPFilter.h" #include US_BEGIN_NAMESPACE -template -const bool ServiceTrackerPrivate::DEBUG_OUTPUT = true; - -template -ServiceTrackerPrivate::ServiceTrackerPrivate( - ServiceTracker* st, ModuleContext* context, - const ServiceReference& reference, - ServiceTrackerCustomizer* customizer) +template +const bool ServiceTrackerPrivate::DEBUG_OUTPUT = true; + +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, ModuleContext* context, + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer) : context(context), customizer(customizer), trackReference(reference), - trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) + trackedService(0), cachedReference(), cachedService(TTT::DefaultValue()), q_ptr(st) { this->customizer = customizer ? customizer : q_func(); std::stringstream ss; ss << "(" << ServiceConstants::SERVICE_ID() << "=" << any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())) << ")"; this->listenerFilter = ss.str(); try { this->filter = LDAPFilter(listenerFilter); } catch (const std::invalid_argument& e) { /* * we could only get this exception if the ServiceReference was * invalid */ std::invalid_argument ia(std::string("unexpected std::invalid_argument exception: ") + e.what()); throw ia; } } -template -ServiceTrackerPrivate::ServiceTrackerPrivate( - ServiceTracker* st, +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, ModuleContext* context, const std::string& clazz, - ServiceTrackerCustomizer* customizer) + ServiceTrackerCustomizer* customizer) : context(context), customizer(customizer), trackClass(clazz), - trackReference(0), trackedService(0), cachedReference(0), - cachedService(0), q_ptr(st) + trackReference(), trackedService(0), cachedReference(), + cachedService(TTT::DefaultValue()), q_ptr(st) { this->customizer = customizer ? customizer : q_func(); this->listenerFilter = std::string("(") + US_PREPEND_NAMESPACE(ServiceConstants)::OBJECTCLASS() + "=" + clazz + ")"; try { this->filter = LDAPFilter(listenerFilter); } catch (const std::invalid_argument& e) { /* * we could only get this exception if the clazz argument was * malformed */ std::invalid_argument ia( std::string("unexpected std::invalid_argument exception: ") + e.what()); throw ia; } } -template -ServiceTrackerPrivate::ServiceTrackerPrivate( - ServiceTracker* st, +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, ModuleContext* context, const LDAPFilter& filter, - ServiceTrackerCustomizer* customizer) + ServiceTrackerCustomizer* customizer) : context(context), filter(filter), customizer(customizer), - listenerFilter(filter.ToString()), trackReference(0), - trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) + listenerFilter(filter.ToString()), trackReference(), + trackedService(0), cachedReference(), cachedService(TTT::DefaultValue()), q_ptr(st) { this->customizer = customizer ? customizer : q_func(); if (context == 0) { throw std::invalid_argument("The module context cannot be null."); } } -template -ServiceTrackerPrivate::~ServiceTrackerPrivate() +template +ServiceTrackerPrivate::~ServiceTrackerPrivate() { } -template -std::list ServiceTrackerPrivate::GetInitialReferences( +template +std::vector > ServiceTrackerPrivate::GetInitialReferences( const std::string& className, const std::string& filterString) { - return context->GetServiceReferences(className, filterString); + std::vector > result; + std::vector refs = context->GetServiceReferences(className, filterString); + for(std::vector::const_iterator iter = refs.begin(); + iter != refs.end(); ++iter) + { + ServiceReference ref(*iter); + if (ref) + { + result.push_back(ref); + } + } + return result; } -template -void ServiceTrackerPrivate::GetServiceReferences_unlocked(std::list& refs, TrackedService* t) const +template +void ServiceTrackerPrivate::GetServiceReferences_unlocked(std::vector >& refs, TrackedService* t) const { if (t->Size() == 0) { return; } t->GetTracked(refs); } -template -TrackedService* ServiceTrackerPrivate::Tracked() const +template +TrackedService* ServiceTrackerPrivate::Tracked() const { return trackedService; } -template -void ServiceTrackerPrivate::Modified() +template +void ServiceTrackerPrivate::Modified() { cachedReference = 0; /* clear cached value */ - cachedService = 0; /* clear cached value */ + TTT::Dispose(cachedService); /* clear cached value */ US_DEBUG(DEBUG_OUTPUT) << "ServiceTracker::Modified(): " << filter; } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usTrackedService.tpp b/Core/CppMicroServices/src/service/usTrackedService.tpp similarity index 72% rename from Core/Code/CppMicroServices/src/service/usTrackedService.tpp rename to Core/CppMicroServices/src/service/usTrackedService.tpp index 8917c200fd..8851affbbe 100644 --- a/Core/Code/CppMicroServices/src/service/usTrackedService.tpp +++ b/Core/CppMicroServices/src/service/usTrackedService.tpp @@ -1,123 +1,124 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ US_BEGIN_NAMESPACE -template -TrackedService::TrackedService(ServiceTracker* serviceTracker, - ServiceTrackerCustomizer* customizer) +template +TrackedService::TrackedService(ServiceTracker* serviceTracker, + ServiceTrackerCustomizer* customizer) : serviceTracker(serviceTracker), customizer(customizer) { } -template -void TrackedService::ServiceChanged(const ServiceEvent event) +template +void TrackedService::ServiceChanged(const ServiceEvent event) { /* * Check if we had a delayed call (which could happen when we * close). */ if (this->closed) { return; } - ServiceReference reference = event.GetServiceReference(); + ServiceReference reference = event.GetServiceReference(InterfaceT()); US_DEBUG(serviceTracker->d->DEBUG_OUTPUT) << "TrackedService::ServiceChanged[" << event.GetType() << "]: " << reference; switch (event.GetType()) { case ServiceEvent::REGISTERED : case ServiceEvent::MODIFIED : { if (!serviceTracker->d->listenerFilter.empty()) { // service listener added with filter this->Track(reference, event); /* * If the customizer throws an unchecked exception, it * is safe to let it propagate */ } else { // service listener added without filter if (serviceTracker->d->filter.Match(reference)) { this->Track(reference, event); /* * If the customizer throws an unchecked exception, * it is safe to let it propagate */ } else { this->Untrack(reference, event); /* * If the customizer throws an unchecked exception, * it is safe to let it propagate */ } } break; } case ServiceEvent::MODIFIED_ENDMATCH : case ServiceEvent::UNREGISTERING : this->Untrack(reference, event); /* * If the customizer throws an unchecked exception, it is * safe to let it propagate */ break; } } -template -void TrackedService::Modified() +template +void TrackedService::Modified() { Superclass::Modified(); /* increment the modification count */ serviceTracker->d->Modified(); } -template -T TrackedService::CustomizerAdding(ServiceReference item, +template +typename TrackedService::T +TrackedService::CustomizerAdding(ServiceReference item, const ServiceEvent& /*related*/) { return customizer->AddingService(item); } -template -void TrackedService::CustomizerModified(ServiceReference item, - const ServiceEvent& /*related*/, - T object) +template +void TrackedService::CustomizerModified(ServiceReference item, + const ServiceEvent& /*related*/, + T object) { customizer->ModifiedService(item, object); } -template -void TrackedService::CustomizerRemoved(ServiceReference item, - const ServiceEvent& /*related*/, - T object) +template +void TrackedService::CustomizerRemoved(ServiceReference item, + const ServiceEvent& /*related*/, + T object) { customizer->RemovedService(item, object); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h b/Core/CppMicroServices/src/service/usTrackedServiceListener_p.h similarity index 96% rename from Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h rename to Core/CppMicroServices/src/service/usTrackedServiceListener_p.h index f70aa53365..7870bdbfd5 100644 --- a/Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h +++ b/Core/CppMicroServices/src/service/usTrackedServiceListener_p.h @@ -1,51 +1,51 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USTRACKEDSERVICELISTENER_H #define USTRACKEDSERVICELISTENER_H #include "usServiceEvent.h" US_BEGIN_NAMESPACE /** * This class is not intended to be used directly. It is exported to support * the CppMicroServices module system. */ -struct TrackedServiceListener // : public US_BASECLASS_NAME +struct TrackedServiceListener { virtual ~TrackedServiceListener() {} /** * Slot connected to service events for the * ServiceTracker class. This method must NOT be * synchronized to avoid deadlock potential. * * @param event ServiceEvent object from the framework. */ virtual void ServiceChanged(const ServiceEvent event) = 0; }; US_END_NAMESPACE #endif // USTRACKEDSERVICELISTENER_H diff --git a/Core/Code/CppMicroServices/src/service/usTrackedService_p.h b/Core/CppMicroServices/src/service/usTrackedService_p.h similarity index 81% rename from Core/Code/CppMicroServices/src/service/usTrackedService_p.h rename to Core/CppMicroServices/src/service/usTrackedService_p.h index 79b366e217..7f0aa6378f 100644 --- a/Core/Code/CppMicroServices/src/service/usTrackedService_p.h +++ b/Core/CppMicroServices/src/service/usTrackedService_p.h @@ -1,107 +1,110 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USTRACKEDSERVICE_H #define USTRACKEDSERVICE_H #include "usTrackedServiceListener_p.h" #include "usModuleAbstractTracked_p.h" #include "usServiceEvent.h" US_BEGIN_NAMESPACE /** * This class is not intended to be used directly. It is exported to support * the CppMicroServices module system. */ -template +template class TrackedService : public TrackedServiceListener, - public ModuleAbstractTracked + public ModuleAbstractTracked, TTT, ServiceEvent> { public: - TrackedService(ServiceTracker* serviceTracker, - ServiceTrackerCustomizer* customizer); + + typedef typename TTT::TrackedType T; + + TrackedService(ServiceTracker* serviceTracker, + ServiceTrackerCustomizer* customizer); /** * Method connected to service events for the * ServiceTracker class. This method must NOT be * synchronized to avoid deadlock potential. * * @param event ServiceEvent object from the framework. */ void ServiceChanged(const ServiceEvent event); private: - typedef ModuleAbstractTracked Superclass; + typedef ModuleAbstractTracked, TTT, ServiceEvent> Superclass; - ServiceTracker* serviceTracker; - ServiceTrackerCustomizer* customizer; + ServiceTracker* serviceTracker; + ServiceTrackerCustomizer* customizer; /** * Increment the tracking count and tell the tracker there was a * modification. * * @GuardedBy this */ void Modified(); /** * Call the specific customizer adding method. This method must not be * called while synchronized on this object. * * @param item Item to be tracked. * @param related Action related object. * @return Customized object for the tracked item or null * if the item is not to be tracked. */ - T CustomizerAdding(ServiceReference item, const ServiceEvent& related); + T CustomizerAdding(ServiceReference item, const ServiceEvent& related); /** * Call the specific customizer modified method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ - void CustomizerModified(ServiceReference item, + void CustomizerModified(ServiceReference item, const ServiceEvent& related, T object) ; /** * Call the specific customizer removed method. This method must not be * called while synchronized on this object. * * @param item Tracked item. * @param related Action related object. * @param object Customized object for the tracked item. */ - void CustomizerRemoved(ServiceReference item, + void CustomizerRemoved(ServiceReference item, const ServiceEvent& related, T object) ; }; US_END_NAMESPACE #include "usTrackedService.tpp" #endif // USTRACKEDSERVICE_H diff --git a/Core/Code/CppMicroServices/src/util/dirent_win32_p.h b/Core/CppMicroServices/src/util/dirent_win32_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/dirent_win32_p.h rename to Core/CppMicroServices/src/util/dirent_win32_p.h diff --git a/Core/CppMicroServices/src/util/json_p.h b/Core/CppMicroServices/src/util/json_p.h new file mode 100644 index 0000000000..0ab8e50d88 --- /dev/null +++ b/Core/CppMicroServices/src/util/json_p.h @@ -0,0 +1,1855 @@ +/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/). +/// It is intented to be used with #include + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + +/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. + +*/ + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + + + + + +#ifndef JSON_AMALGATED_H_INCLUDED +# define JSON_AMALGATED_H_INCLUDED +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +#define JSON_IS_AMALGATED + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_CONFIG_H_INCLUDED +# define JSON_CONFIG_H_INCLUDED + +/// If defined, indicates that json library is embedded in CppTL library. +//# define JSON_IN_CPPTL 1 + +/// If defined, indicates that json may leverage CppTL library +//# define JSON_USE_CPPTL 1 +/// If defined, indicates that cpptl vector based map should be used instead of std::map +/// as Value container. +//# define JSON_USE_CPPTL_SMALLMAP 1 +/// If defined, indicates that Json specific container should be used +/// (hash table & simple deque container with customizable allocator). +/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332 +//# define JSON_VALUE_USE_INTERNAL_MAP 1 +/// Force usage of standard new/malloc based allocator instead of memory pool based allocator. +/// The memory pools allocator used optimization (initializing Value and ValueInternalLink +/// as if it was a POD) that may cause some validation tool to report errors. +/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined. +//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1 + +/// If defined, indicates that Json use exception to report invalid type manipulation +/// instead of C assert macro. +# define JSON_USE_EXCEPTION 1 + +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +/// Remarks: it is automatically defined in the generated amalgated header. +#define JSON_IS_AMALGAMATION + + +# ifdef JSON_IN_CPPTL +# include +# ifndef JSON_USE_CPPTL +# define JSON_USE_CPPTL 1 +# endif +# endif + +# ifdef JSON_IN_CPPTL +# define JSON_API CPPTL_API +# elif defined(JSON_DLL_BUILD) +# define JSON_API __declspec(dllexport) +# elif defined(JSON_DLL) +# define JSON_API __declspec(dllimport) +# else +# define JSON_API +# endif + +// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for integer +// Storages, and 64 bits integer support is disabled. +// #define JSON_NO_INT64 1 + +#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6 +// Microsoft Visual Studio 6 only support conversion from __int64 to double +// (no conversion from unsigned __int64). +#define JSON_USE_INT64_DOUBLE_CONVERSION 1 +#endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6 + +#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008 +/// Indicates that the following function is deprecated. +# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) +#endif + +#if !defined(JSONCPP_DEPRECATED) +# define JSONCPP_DEPRECATED(message) +#endif // if !defined(JSONCPP_DEPRECATED) + +namespace Json { + typedef int Int; + typedef unsigned int UInt; +# if defined(JSON_NO_INT64) + typedef int LargestInt; + typedef unsigned int LargestUInt; +# undef JSON_HAS_INT64 +# else // if defined(JSON_NO_INT64) + // For Microsoft Visual use specific types as long long is not supported +# if defined(_MSC_VER) // Microsoft Visual Studio + typedef __int64 Int64; + typedef unsigned __int64 UInt64; +# else // if defined(_MSC_VER) // Other platforms, use long long + typedef long long int Int64; + typedef unsigned long long int UInt64; +# endif // if defined(_MSC_VER) + typedef Int64 LargestInt; + typedef UInt64 LargestUInt; +# define JSON_HAS_INT64 +# endif // if defined(JSON_NO_INT64) +} // end namespace Json + + +#endif // JSON_CONFIG_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_FORWARDS_H_INCLUDED +# define JSON_FORWARDS_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "config.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + + // writer.h + class FastWriter; + class StyledWriter; + + // reader.h + class Reader; + + // features.h + class Features; + + // value.h + typedef unsigned int ArrayIndex; + class StaticString; + class Path; + class PathArgument; + class Value; + class ValueIteratorBase; + class ValueIterator; + class ValueConstIterator; +#ifdef JSON_VALUE_USE_INTERNAL_MAP + class ValueMapAllocator; + class ValueInternalLink; + class ValueInternalArray; + class ValueInternalMap; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + +} // namespace Json + + +#endif // JSON_FORWARDS_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_FEATURES_H_INCLUDED +# define CPPTL_JSON_FEATURES_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + + /** \brief Configuration passed to reader and writer. + * This configuration object can be used to force the Reader or Writer + * to behave in a standard conforming way. + */ + class JSON_API Features + { + public: + /** \brief A configuration that allows all features and assumes all strings are UTF-8. + * - C & C++ comments are allowed + * - Root object can be any JSON value + * - Assumes Value strings are encoded in UTF-8 + */ + static Features all(); + + /** \brief A configuration that is strictly compatible with the JSON specification. + * - Comments are forbidden. + * - Root object must be either an array or an object value. + * - Assumes Value strings are encoded in UTF-8 + */ + static Features strictMode(); + + /** \brief Initialize the configuration like JsonConfig::allFeatures; + */ + Features(); + + /// \c true if comments are allowed. Default: \c true. + bool allowComments_; + + /// \c true if root must be either an array or an object value. Default: \c false. + bool strictRoot_; + }; + +} // namespace Json + +#endif // CPPTL_JSON_FEATURES_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_H_INCLUDED +# define CPPTL_JSON_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include + +# ifndef JSON_USE_CPPTL_SMALLMAP +# include +# else +# include +# endif +# ifdef JSON_USE_CPPTL +# include +# endif + +/** \brief JSON (JavaScript Object Notation). + */ +namespace Json { + + /** \brief Type of the value held by a Value object. + */ + enum ValueType + { + nullValue = 0, ///< 'null' value + intValue, ///< signed integer value + uintValue, ///< unsigned integer value + realValue, ///< double value + stringValue, ///< UTF-8 string value + booleanValue, ///< bool value + arrayValue, ///< array value (ordered list) + objectValue ///< object value (collection of name/value pairs). + }; + + enum CommentPlacement + { + commentBefore = 0, ///< a comment placed on the line before a value + commentAfterOnSameLine, ///< a comment just after a value on the same line + commentAfter, ///< a comment on the line after a value (only make sense for root value) + numberOfCommentPlacement + }; + +//# ifdef JSON_USE_CPPTL +// typedef CppTL::AnyEnumerator EnumMemberNames; +// typedef CppTL::AnyEnumerator EnumValues; +//# endif + + /** \brief Lightweight wrapper to tag static string. + * + * Value constructor and objectValue member assignement takes advantage of the + * StaticString and avoid the cost of string duplication when storing the + * string or the member name. + * + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + class JSON_API StaticString + { + public: + explicit StaticString( const char *czstring ) + : str_( czstring ) + { + } + + operator const char *() const + { + return str_; + } + + const char *c_str() const + { + return str_; + } + + private: + const char *str_; + }; + + /** \brief Represents a JSON value. + * + * This class is a discriminated union wrapper that can represents a: + * - signed integer [range: Value::minInt - Value::maxInt] + * - unsigned integer (range: 0 - Value::maxUInt) + * - double + * - UTF-8 string + * - boolean + * - 'null' + * - an ordered list of Value + * - collection of name/value pairs (javascript object) + * + * The type of the held value is represented by a #ValueType and + * can be obtained using type(). + * + * values of an #objectValue or #arrayValue can be accessed using operator[]() methods. + * Non const methods will automatically create the a #nullValue element + * if it does not exist. + * The sequence of an #arrayValue will be automatically resize and initialized + * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. + * + * The get() methods can be used to obtanis default value in the case the required element + * does not exist. + * + * It is possible to iterate over the list of a #objectValue values using + * the getMemberNames() method. + */ + class JSON_API Value + { + friend class ValueIteratorBase; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + friend class ValueInternalLink; + friend class ValueInternalMap; +# endif + public: + typedef std::vector Members; + typedef ValueIterator iterator; + typedef ValueConstIterator const_iterator; + typedef Json::UInt UInt; + typedef Json::Int Int; +# if defined(JSON_HAS_INT64) + typedef Json::UInt64 UInt64; + typedef Json::Int64 Int64; +#endif // defined(JSON_HAS_INT64) + typedef Json::LargestInt LargestInt; + typedef Json::LargestUInt LargestUInt; + typedef Json::ArrayIndex ArrayIndex; + + static const Value null; + /// Minimum signed integer value that can be stored in a Json::Value. + static const LargestInt minLargestInt; + /// Maximum signed integer value that can be stored in a Json::Value. + static const LargestInt maxLargestInt; + /// Maximum unsigned integer value that can be stored in a Json::Value. + static const LargestUInt maxLargestUInt; + + /// Minimum signed int value that can be stored in a Json::Value. + static const Int minInt; + /// Maximum signed int value that can be stored in a Json::Value. + static const Int maxInt; + /// Maximum unsigned int value that can be stored in a Json::Value. + static const UInt maxUInt; + + /// Minimum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 minInt64; + /// Maximum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 maxInt64; + /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. + static const UInt64 maxUInt64; + + private: +#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION +# ifndef JSON_VALUE_USE_INTERNAL_MAP + class CZString + { + public: + enum DuplicationPolicy + { + noDuplication = 0, + duplicate, + duplicateOnCopy + }; + CZString( ArrayIndex index ); + CZString( const char *cstr, DuplicationPolicy allocate ); + CZString( const CZString &other ); + ~CZString(); + CZString &operator =( const CZString &other ); + bool operator<( const CZString &other ) const; + bool operator==( const CZString &other ) const; + ArrayIndex index() const; + const char *c_str() const; + bool isStaticString() const; + private: + void swap( CZString &other ); + const char *cstr_; + ArrayIndex index_; + }; + + public: +# ifndef JSON_USE_CPPTL_SMALLMAP + typedef std::map ObjectValues; +# else + typedef CppTL::SmallMap ObjectValues; +# endif // ifndef JSON_USE_CPPTL_SMALLMAP +# endif // ifndef JSON_VALUE_USE_INTERNAL_MAP +#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + public: + /** \brief Create a default Value of the given type. + + This is a very useful constructor. + To create an empty array, pass arrayValue. + To create an empty object, pass objectValue. + Another Value can then be set to this one by assignment. + This is useful since clear() and resize() will not alter types. + + Examples: + \code + Json::Value null_value; // null + Json::Value arr_value(Json::arrayValue); // [] + Json::Value obj_value(Json::objectValue); // {} + \endcode + */ + Value( ValueType type = nullValue ); + Value( Int value ); + Value( UInt value ); +#if defined(JSON_HAS_INT64) + Value( Int64 value ); + Value( UInt64 value ); +#endif // if defined(JSON_HAS_INT64) + Value( double value ); + Value( const char *value ); + Value( const char *beginValue, const char *endValue ); + /** \brief Constructs a value from a static string. + + * Like other value string constructor but do not duplicate the string for + * internal storage. The given string must remain alive after the call to this + * constructor. + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * \endcode + */ + Value( const StaticString &value ); + Value( const std::string &value ); +# ifdef JSON_USE_CPPTL + Value( const CppTL::ConstString &value ); +# endif + Value( bool value ); + Value( const Value &other ); + ~Value(); + + Value &operator=( const Value &other ); + /// Swap values. + /// \note Currently, comments are intentionally not swapped, for + /// both logic and efficiency. + void swap( Value &other ); + + ValueType type() const; + + bool operator <( const Value &other ) const; + bool operator <=( const Value &other ) const; + bool operator >=( const Value &other ) const; + bool operator >( const Value &other ) const; + + bool operator ==( const Value &other ) const; + bool operator !=( const Value &other ) const; + + int compare( const Value &other ) const; + + const char *asCString() const; + std::string asString() const; +# ifdef JSON_USE_CPPTL + CppTL::ConstString asConstString() const; +# endif + Int asInt() const; + UInt asUInt() const; + Int64 asInt64() const; + UInt64 asUInt64() const; + LargestInt asLargestInt() const; + LargestUInt asLargestUInt() const; + float asFloat() const; + double asDouble() const; + bool asBool() const; + + bool isNull() const; + bool isBool() const; + bool isInt() const; + bool isUInt() const; + bool isIntegral() const; + bool isDouble() const; + bool isNumeric() const; + bool isString() const; + bool isArray() const; + bool isObject() const; + + bool isConvertibleTo( ValueType other ) const; + + /// Number of values in array or object + ArrayIndex size() const; + + /// \brief Return true if empty array, empty object, or null; + /// otherwise, false. + bool empty() const; + + /// Return isNull() + bool operator!() const; + + /// Remove all object members and array elements. + /// \pre type() is arrayValue, objectValue, or nullValue + /// \post type() is unchanged + void clear(); + + /// Resize the array to size elements. + /// New elements are initialized to null. + /// May only be called on nullValue or arrayValue. + /// \pre type() is arrayValue or nullValue + /// \post type() is arrayValue + void resize( ArrayIndex size ); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value &operator[]( ArrayIndex index ); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value &operator[]( int index ); + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value &operator[]( ArrayIndex index ) const; + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value &operator[]( int index ) const; + + /// If the array contains at least index+1 elements, returns the element value, + /// otherwise returns defaultValue. + Value get( ArrayIndex index, + const Value &defaultValue ) const; + /// Return true if index < size(). + bool isValidIndex( ArrayIndex index ) const; + /// \brief Append value to array at the end. + /// + /// Equivalent to jsonvalue[jsonvalue.size()] = value; + Value &append( const Value &value ); + + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const char *key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const char *key ) const; + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const std::string &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const std::string &key ) const; + /** \brief Access an object value by name, create a null member if it does not exist. + + * If the object as no entry for that name, then the member name used to store + * the new entry is not duplicated. + * Example of use: + * \code + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + Value &operator[]( const StaticString &key ); +# ifdef JSON_USE_CPPTL + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const CppTL::ConstString &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const CppTL::ConstString &key ) const; +# endif + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const char *key, + const Value &defaultValue ) const; + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const std::string &key, + const Value &defaultValue ) const; +# ifdef JSON_USE_CPPTL + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const CppTL::ConstString &key, + const Value &defaultValue ) const; +# endif + /// \brief Remove and return the named member. + /// + /// Do nothing if it did not exist. + /// \return the removed Value, or null. + /// \pre type() is objectValue or nullValue + /// \post type() is unchanged + Value removeMember( const char* key ); + /// Same as removeMember(const char*) + Value removeMember( const std::string &key ); + + /// Return true if the object has a member named key. + bool isMember( const char *key ) const; + /// Return true if the object has a member named key. + bool isMember( const std::string &key ) const; +# ifdef JSON_USE_CPPTL + /// Return true if the object has a member named key. + bool isMember( const CppTL::ConstString &key ) const; +# endif + + /// \brief Return a list of the member names. + /// + /// If null, return an empty list. + /// \pre type() is objectValue or nullValue + /// \post if type() was nullValue, it remains nullValue + Members getMemberNames() const; + +//# ifdef JSON_USE_CPPTL +// EnumMemberNames enumMemberNames() const; +// EnumValues enumValues() const; +//# endif + + /// Comments must be //... or /* ... */ + void setComment( const char *comment, + CommentPlacement placement ); + /// Comments must be //... or /* ... */ + void setComment( const std::string &comment, + CommentPlacement placement ); + bool hasComment( CommentPlacement placement ) const; + /// Include delimiters and embedded newlines. + std::string getComment( CommentPlacement placement ) const; + + std::string toStyledString() const; + + const_iterator begin() const; + const_iterator end() const; + + iterator begin(); + iterator end(); + + private: + Value &resolveReference( const char *key, + bool isStatic ); + +# ifdef JSON_VALUE_USE_INTERNAL_MAP + inline bool isItemAvailable() const + { + return itemIsUsed_ == 0; + } + + inline void setItemUsed( bool isUsed = true ) + { + itemIsUsed_ = isUsed ? 1 : 0; + } + + inline bool isMemberNameStatic() const + { + return memberNameIsStatic_ == 0; + } + + inline void setMemberNameIsStatic( bool isStatic ) + { + memberNameIsStatic_ = isStatic ? 1 : 0; + } +# endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP + + private: + struct CommentInfo + { + CommentInfo(); + ~CommentInfo(); + + void setComment( const char *text ); + + char *comment_; + }; + + //struct MemberNamesTransform + //{ + // typedef const char *result_type; + // const char *operator()( const CZString &name ) const + // { + // return name.c_str(); + // } + //}; + + union ValueHolder + { + LargestInt int_; + LargestUInt uint_; + double real_; + bool bool_; + char *string_; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + ValueInternalArray *array_; + ValueInternalMap *map_; +#else + ObjectValues *map_; +# endif + } value_; + ValueType type_ : 8; + int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. +# ifdef JSON_VALUE_USE_INTERNAL_MAP + unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container. + int memberNameIsStatic_ : 1; // used by the ValueInternalMap container. +# endif + CommentInfo *comments_; + }; + + + /** \brief Experimental and untested: represents an element of the "path" to access a node. + */ + class PathArgument + { + public: + friend class Path; + + PathArgument(); + PathArgument( ArrayIndex index ); + PathArgument( const char *key ); + PathArgument( const std::string &key ); + + private: + enum Kind + { + kindNone = 0, + kindIndex, + kindKey + }; + std::string key_; + ArrayIndex index_; + Kind kind_; + }; + + /** \brief Experimental and untested: represents a "path" to access a node. + * + * Syntax: + * - "." => root node + * - ".[n]" => elements at index 'n' of root node (an array value) + * - ".name" => member named 'name' of root node (an object value) + * - ".name1.name2.name3" + * - ".[0][1][2].name1[3]" + * - ".%" => member name is provided as parameter + * - ".[%]" => index is provied as parameter + */ + class Path + { + public: + Path( const std::string &path, + const PathArgument &a1 = PathArgument(), + const PathArgument &a2 = PathArgument(), + const PathArgument &a3 = PathArgument(), + const PathArgument &a4 = PathArgument(), + const PathArgument &a5 = PathArgument() ); + + const Value &resolve( const Value &root ) const; + Value resolve( const Value &root, + const Value &defaultValue ) const; + /// Creates the "path" to access the specified node and returns a reference on the node. + Value &make( Value &root ) const; + + private: + typedef std::vector InArgs; + typedef std::vector Args; + + void makePath( const std::string &path, + const InArgs &in ); + void addPathInArg( const std::string &path, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ); + void invalidPath( const std::string &path, + int location ); + + Args args_; + }; + + + +#ifdef JSON_VALUE_USE_INTERNAL_MAP + /** \brief Allocator to customize Value internal map. + * Below is an example of a simple implementation (default implementation actually + * use memory pool for speed). + * \code + class DefaultValueMapAllocator : public ValueMapAllocator + { + public: // overridden from ValueMapAllocator + virtual ValueInternalMap *newMap() + { + return new ValueInternalMap(); + } + + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) + { + return new ValueInternalMap( other ); + } + + virtual void destructMap( ValueInternalMap *map ) + { + delete map; + } + + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) + { + return new ValueInternalLink[size]; + } + + virtual void releaseMapBuckets( ValueInternalLink *links ) + { + delete [] links; + } + + virtual ValueInternalLink *allocateMapLink() + { + return new ValueInternalLink(); + } + + virtual void releaseMapLink( ValueInternalLink *link ) + { + delete link; + } + }; + * \endcode + */ + class JSON_API ValueMapAllocator + { + public: + virtual ~ValueMapAllocator(); + virtual ValueInternalMap *newMap() = 0; + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0; + virtual void destructMap( ValueInternalMap *map ) = 0; + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0; + virtual void releaseMapBuckets( ValueInternalLink *links ) = 0; + virtual ValueInternalLink *allocateMapLink() = 0; + virtual void releaseMapLink( ValueInternalLink *link ) = 0; + }; + + /** \brief ValueInternalMap hash-map bucket chain link (for internal use only). + * \internal previous_ & next_ allows for bidirectional traversal. + */ + class JSON_API ValueInternalLink + { + public: + enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture. + enum InternalFlags { + flagAvailable = 0, + flagUsed = 1 + }; + + ValueInternalLink(); + + ~ValueInternalLink(); + + Value items_[itemPerLink]; + char *keys_[itemPerLink]; + ValueInternalLink *previous_; + ValueInternalLink *next_; + }; + + + /** \brief A linked page based hash-table implementation used internally by Value. + * \internal ValueInternalMap is a tradional bucket based hash-table, with a linked + * list in each bucket to handle collision. There is an addional twist in that + * each node of the collision linked list is a page containing a fixed amount of + * value. This provides a better compromise between memory usage and speed. + * + * Each bucket is made up of a chained list of ValueInternalLink. The last + * link of a given bucket can be found in the 'previous_' field of the following bucket. + * The last link of the last bucket is stored in tailLink_ as it has no following bucket. + * Only the last link of a bucket may contains 'available' item. The last link always + * contains at least one element unless is it the bucket one very first link. + */ + class JSON_API ValueInternalMap + { + friend class ValueIteratorBase; + friend class Value; + public: + typedef unsigned int HashKey; + typedef unsigned int BucketIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState + { + IteratorState() + : map_(0) + , link_(0) + , itemIndex_(0) + , bucketIndex_(0) + { + } + ValueInternalMap *map_; + ValueInternalLink *link_; + BucketIndex itemIndex_; + BucketIndex bucketIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalMap(); + ValueInternalMap( const ValueInternalMap &other ); + ValueInternalMap &operator =( const ValueInternalMap &other ); + ~ValueInternalMap(); + + void swap( ValueInternalMap &other ); + + BucketIndex size() const; + + void clear(); + + bool reserveDelta( BucketIndex growth ); + + bool reserve( BucketIndex newItemCount ); + + const Value *find( const char *key ) const; + + Value *find( const char *key ); + + Value &resolveReference( const char *key, + bool isStatic ); + + void remove( const char *key ); + + void doActualRemove( ValueInternalLink *link, + BucketIndex index, + BucketIndex bucketIndex ); + + ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex ); + + Value &setNewItem( const char *key, + bool isStatic, + ValueInternalLink *link, + BucketIndex index ); + + Value &unsafeAdd( const char *key, + bool isStatic, + HashKey hashedKey ); + + HashKey hash( const char *key ) const; + + int compare( const ValueInternalMap &other ) const; + + private: + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void incrementBucket( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static const char *key( const IteratorState &iterator ); + static const char *key( const IteratorState &iterator, bool &isStatic ); + static Value &value( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + + private: + ValueInternalLink *buckets_; + ValueInternalLink *tailLink_; + BucketIndex bucketsSize_; + BucketIndex itemCount_; + }; + + /** \brief A simplified deque implementation used internally by Value. + * \internal + * It is based on a list of fixed "page", each page contains a fixed number of items. + * Instead of using a linked-list, a array of pointer is used for fast item look-up. + * Look-up for an element is as follow: + * - compute page index: pageIndex = itemIndex / itemsPerPage + * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage] + * + * Insertion is amortized constant time (only the array containing the index of pointers + * need to be reallocated when items are appended). + */ + class JSON_API ValueInternalArray + { + friend class Value; + friend class ValueIteratorBase; + public: + enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo. + typedef Value::ArrayIndex ArrayIndex; + typedef unsigned int PageIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState // Must be a POD + { + IteratorState() + : array_(0) + , currentPageIndex_(0) + , currentItemIndex_(0) + { + } + ValueInternalArray *array_; + Value **currentPageIndex_; + unsigned int currentItemIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalArray(); + ValueInternalArray( const ValueInternalArray &other ); + ValueInternalArray &operator =( const ValueInternalArray &other ); + ~ValueInternalArray(); + void swap( ValueInternalArray &other ); + + void clear(); + void resize( ArrayIndex newSize ); + + Value &resolveReference( ArrayIndex index ); + + Value *find( ArrayIndex index ) const; + + ArrayIndex size() const; + + int compare( const ValueInternalArray &other ) const; + + private: + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static Value &dereference( const IteratorState &iterator ); + static Value &unsafeDereference( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + static ArrayIndex indexOf( const IteratorState &iterator ); + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + void makeIterator( IteratorState &it, ArrayIndex index ) const; + + void makeIndexValid( ArrayIndex index ); + + Value **pages_; + ArrayIndex size_; + PageIndex pageCount_; + }; + + /** \brief Experimental: do not use. Allocator to customize Value internal array. + * Below is an example of a simple implementation (actual implementation use + * memory pool). + \code +class DefaultValueArrayAllocator : public ValueArrayAllocator +{ +public: // overridden from ValueArrayAllocator + virtual ~DefaultValueArrayAllocator() + { + } + + virtual ValueInternalArray *newArray() + { + return new ValueInternalArray(); + } + + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) + { + return new ValueInternalArray( other ); + } + + virtual void destruct( ValueInternalArray *array ) + { + delete array; + } + + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) + { + ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; + if ( minNewIndexCount > newIndexCount ) + newIndexCount = minNewIndexCount; + void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); + if ( !newIndexes ) + throw std::bad_alloc(); + indexCount = newIndexCount; + indexes = static_cast( newIndexes ); + } + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) + { + if ( indexes ) + free( indexes ); + } + + virtual Value *allocateArrayPage() + { + return static_cast( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) ); + } + + virtual void releaseArrayPage( Value *value ) + { + if ( value ) + free( value ); + } +}; + \endcode + */ + class JSON_API ValueArrayAllocator + { + public: + virtual ~ValueArrayAllocator(); + virtual ValueInternalArray *newArray() = 0; + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0; + virtual void destructArray( ValueInternalArray *array ) = 0; + /** \brief Reallocate array page index. + * Reallocates an array of pointer on each page. + * \param indexes [input] pointer on the current index. May be \c NULL. + * [output] pointer on the new index of at least + * \a minNewIndexCount pages. + * \param indexCount [input] current number of pages in the index. + * [output] number of page the reallocated index can handle. + * \b MUST be >= \a minNewIndexCount. + * \param minNewIndexCount Minimum number of page the new index must be able to + * handle. + */ + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) = 0; + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) = 0; + virtual Value *allocateArrayPage() = 0; + virtual void releaseArrayPage( Value *value ) = 0; + }; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + + + /** \brief base class for Value iterators. + * + */ + class ValueIteratorBase + { + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef ValueIteratorBase SelfType; + + ValueIteratorBase(); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIteratorBase( const Value::ObjectValues::iterator ¤t ); +#else + ValueIteratorBase( const ValueInternalArray::IteratorState &state ); + ValueIteratorBase( const ValueInternalMap::IteratorState &state ); +#endif + + bool operator ==( const SelfType &other ) const + { + return isEqual( other ); + } + + bool operator !=( const SelfType &other ) const + { + return !isEqual( other ); + } + + difference_type operator -( const SelfType &other ) const + { + return computeDistance( other ); + } + + /// Return either the index or the member name of the referenced value as a Value. + Value key() const; + + /// Return the index of the referenced Value. -1 if it is not an arrayValue. + UInt index() const; + + /// Return the member name of the referenced Value. "" if it is not an objectValue. + const char *memberName() const; + + protected: + Value &deref() const; + + void increment(); + + void decrement(); + + difference_type computeDistance( const SelfType &other ) const; + + bool isEqual( const SelfType &other ) const; + + void copy( const SelfType &other ); + + private: +#ifndef JSON_VALUE_USE_INTERNAL_MAP + Value::ObjectValues::iterator current_; + // Indicates that iterator is for a null value. + bool isNull_; +#else + union + { + ValueInternalArray::IteratorState array_; + ValueInternalMap::IteratorState map_; + } iterator_; + bool isArray_; +#endif + }; + + /** \brief const iterator for object and array value. + * + */ + class ValueConstIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef const Value &reference; + typedef const Value *pointer; + typedef ValueConstIterator SelfType; + + ValueConstIterator(); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueConstIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueConstIterator( const ValueInternalArray::IteratorState &state ); + ValueConstIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + SelfType &operator =( const ValueIteratorBase &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + + /** \brief Iterator for object and array value. + */ + class ValueIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef Value &reference; + typedef Value *pointer; + typedef ValueIterator SelfType; + + ValueIterator(); + ValueIterator( const ValueConstIterator &other ); + ValueIterator( const ValueIterator &other ); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueIterator( const ValueInternalArray::IteratorState &state ); + ValueIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + + SelfType &operator =( const SelfType &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + +} // namespace Json + + +#endif // CPPTL_JSON_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_READER_H_INCLUDED +# define CPPTL_JSON_READER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "features.h" +# include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include +# include + +namespace Json { + + /** \brief Unserialize a JSON document into a Value. + * + */ + class JSON_API Reader + { + public: + typedef char Char; + typedef const Char *Location; + + /** \brief Constructs a Reader allowing all features + * for parsing. + */ + Reader(); + + /** \brief Constructs a Reader allowing the specified feature set + * for parsing. + */ + Reader( const Features &features ); + + /** \brief Read a Value from a JSON document. + * \param document UTF-8 encoded string containing the document to read. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const std::string &document, + Value &root, + bool collectComments = true ); + + /** \brief Read a Value from a JSON document. + * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read. + * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read. + \ Must be >= beginDoc. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments = true ); + + /// \brief Parse from input stream. + /// \see Json::operator>>(std::istream&, Json::Value&). + bool parse( std::istream &is, + Value &root, + bool collectComments = true ); + + /** \brief Returns a user friendly string that list errors in the parsed document. + * \return Formatted error message with the list of errors with their location in + * the parsed document. An empty string is returned if no error occurred + * during parsing. + * \deprecated Use getFormattedErrorMessages() instead (typo fix). + */ + JSONCPP_DEPRECATED("Use getFormattedErrorMessages instead") + std::string getFormatedErrorMessages() const; + + /** \brief Returns a user friendly string that list errors in the parsed document. + * \return Formatted error message with the list of errors with their location in + * the parsed document. An empty string is returned if no error occurred + * during parsing. + */ + std::string getFormattedErrorMessages() const; + + private: + enum TokenType + { + tokenEndOfStream = 0, + tokenObjectBegin, + tokenObjectEnd, + tokenArrayBegin, + tokenArrayEnd, + tokenString, + tokenNumber, + tokenTrue, + tokenFalse, + tokenNull, + tokenArraySeparator, + tokenMemberSeparator, + tokenComment, + tokenError + }; + + class Token + { + public: + TokenType type_; + Location start_; + Location end_; + }; + + class ErrorInfo + { + public: + Token token_; + std::string message_; + Location extra_; + }; + + typedef std::deque Errors; + + bool expectToken( TokenType type, Token &token, const char *message ); + bool readToken( Token &token ); + void skipSpaces(); + bool match( Location pattern, + int patternLength ); + bool readComment(); + bool readCStyleComment(); + bool readCppStyleComment(); + bool readString(); + void readNumber(); + bool readValue(); + bool readObject( Token &token ); + bool readArray( Token &token ); + bool decodeNumber( Token &token ); + bool decodeString( Token &token ); + bool decodeString( Token &token, std::string &decoded ); + bool decodeDouble( Token &token ); + bool decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool addError( const std::string &message, + Token &token, + Location extra = 0 ); + bool recoverFromError( TokenType skipUntilToken ); + bool addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ); + void skipUntilSpace(); + Value ¤tValue(); + Char getNextChar(); + void getLocationLineAndColumn( Location location, + int &line, + int &column ) const; + std::string getLocationLineAndColumn( Location location ) const; + void addComment( Location begin, + Location end, + CommentPlacement placement ); + void skipCommentTokens( Token &token ); + + typedef std::stack Nodes; + Nodes nodes_; + Errors errors_; + std::string document_; + Location begin_; + Location end_; + Location current_; + Location lastValueEnd_; + Value *lastValue_; + std::string commentsBefore_; + Features features_; + bool collectComments_; + }; + + /** \brief Read from 'sin' into 'root'. + + Always keep comments from the input JSON. + + This can be used to read a file into a particular sub-object. + For example: + \code + Json::Value root; + cin >> root["dir"]["file"]; + cout << root; + \endcode + Result: + \verbatim + { + "dir": { + "file": { + // The input stream JSON would be nested here. + } + } + } + \endverbatim + \throw std::exception on parse error. + \see Json::operator<<() + */ + std::istream& operator>>( std::istream&, Value& ); + +} // namespace Json + +#endif // CPPTL_JSON_READER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_WRITER_H_INCLUDED +# define JSON_WRITER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +# include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include + +namespace Json { + + class Value; + + /** \brief Abstract class for writers. + */ + class JSON_API Writer + { + public: + virtual ~Writer(); + + virtual std::string write( const Value &root ) = 0; + }; + + /** \brief Outputs a Value in JSON format without formatting (not human friendly). + * + * The JSON document is written in a single line. It is not intended for 'human' consumption, + * but may be usefull to support feature such as RPC where bandwith is limited. + * \sa Reader, Value + */ + class JSON_API FastWriter : public Writer + { + public: + FastWriter(); + virtual ~FastWriter(){} + + void enableYAMLCompatibility(); + + public: // overridden from Writer + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + + std::string document_; + bool yamlCompatiblityEnabled_; + }; + + /** \brief Writes a Value in JSON format in a human friendly way. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledWriter: public Writer + { + public: + StyledWriter(); + virtual ~StyledWriter(){} + + public: // overridden from Writer + /** \brief Serialize a Value in JSON format. + * \param root Value to serialize. + * \return String containing the JSON document that represents the root value. + */ + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::string document_; + std::string indentString_; + int rightMargin_; + int indentSize_; + bool addChildValues_; + }; + + /** \brief Writes a Value in JSON format in a human friendly way, + to a stream rather than to a string. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \param indentation Each level will be indented by this amount extra. + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledStreamWriter + { + public: + StyledStreamWriter( std::string indentation="\t" ); + ~StyledStreamWriter(){} + + public: + /** \brief Serialize a Value in JSON format. + * \param out Stream to write to. (Can be ostringstream, e.g.) + * \param root Value to serialize. + * \note There is no point in deriving from Writer, since write() should not return a value. + */ + void write( std::ostream &out, const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::ostream* document_; + std::string indentString_; + int rightMargin_; + std::string indentation_; + bool addChildValues_; + }; + +# if defined(JSON_HAS_INT64) + std::string JSON_API valueToString( Int value ); + std::string JSON_API valueToString( UInt value ); +# endif // if defined(JSON_HAS_INT64) + std::string JSON_API valueToString( LargestInt value ); + std::string JSON_API valueToString( LargestUInt value ); + std::string JSON_API valueToString( double value ); + std::string JSON_API valueToString( bool value ); + std::string JSON_API valueToQuotedString( const char *value ); + + /// \brief Output using the StyledStreamWriter. + /// \see Json::operator>>() + std::ostream& operator<<( std::ostream&, const Value &root ); + +} // namespace Json + + + +#endif // JSON_WRITER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + + + + + +#endif //ifndef JSON_AMALGATED_H_INCLUDED diff --git a/Core/CppMicroServices/src/util/jsoncpp.cpp b/Core/CppMicroServices/src/util/jsoncpp.cpp new file mode 100644 index 0000000000..8b2781c281 --- /dev/null +++ b/Core/CppMicroServices/src/util/jsoncpp.cpp @@ -0,0 +1,4225 @@ +/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/). +/// It is intented to be used with #include + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + +/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. + +*/ + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + + + + + + +#include + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_tool.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED +# define LIB_JSONCPP_JSON_TOOL_H_INCLUDED + +/* This header provides common string manipulation support, such as UTF-8, + * portable conversion from/to string... + * + * It is an internal header that must not be exposed. + */ + +namespace Json { + +/// Converts a unicode code-point to UTF-8. +static inline std::string +codePointToUTF8(unsigned int cp) +{ + std::string result; + + // based on description from http://en.wikipedia.org/wiki/UTF-8 + + if (cp <= 0x7f) + { + result.resize(1); + result[0] = static_cast(cp); + } + else if (cp <= 0x7FF) + { + result.resize(2); + result[1] = static_cast(0x80 | (0x3f & cp)); + result[0] = static_cast(0xC0 | (0x1f & (cp >> 6))); + } + else if (cp <= 0xFFFF) + { + result.resize(3); + result[2] = static_cast(0x80 | (0x3f & cp)); + result[1] = 0x80 | static_cast((0x3f & (cp >> 6))); + result[0] = 0xE0 | static_cast((0xf & (cp >> 12))); + } + else if (cp <= 0x10FFFF) + { + result.resize(4); + result[3] = static_cast(0x80 | (0x3f & cp)); + result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); + result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); + result[0] = static_cast(0xF0 | (0x7 & (cp >> 18))); + } + + return result; +} + + +/// Returns true if ch is a control character (in range [0,32[). +static inline bool +isControlCharacter(char ch) +{ + return ch > 0 && ch <= 0x1F; +} + + +enum { + /// Constant that specify the size of the buffer that must be passed to uintToString. + uintToStringBufferSize = 3*sizeof(LargestUInt)+1 +}; + +// Defines a char buffer for use with uintToString(). +typedef char UIntToStringBuffer[uintToStringBufferSize]; + + +/** Converts an unsigned integer to string. + * @param value Unsigned interger to convert to string + * @param current Input/Output string buffer. + * Must have at least uintToStringBufferSize chars free. + */ +static inline void +uintToString( LargestUInt value, + char *¤t ) +{ + *--current = 0; + do + { + *--current = char(value % 10) + '0'; + value /= 10; + } + while ( value != 0 ); +} + +} // namespace Json { + +#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_tool.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_reader.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include +# include "json_tool.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#include + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +// Implementation of class Features +// //////////////////////////////// + +Features::Features() + : allowComments_( true ) + , strictRoot_( false ) +{ +} + + +Features +Features::all() +{ + return Features(); +} + + +Features +Features::strictMode() +{ + Features features; + features.allowComments_ = false; + features.strictRoot_ = true; + return features; +} + +// Implementation of class Reader +// //////////////////////////////// + + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4; +} + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4 || c == c5; +} + + +static bool +containsNewLine( Reader::Location begin, + Reader::Location end ) +{ + for ( ;begin < end; ++begin ) + if ( *begin == '\n' || *begin == '\r' ) + return true; + return false; +} + + +// Class Reader +// ////////////////////////////////////////////////////////////////// + +Reader::Reader() + : features_( Features::all() ) +{ +} + + +Reader::Reader( const Features &features ) + : features_( features ) +{ +} + + +bool +Reader::parse( const std::string &document, + Value &root, + bool collectComments ) +{ + document_ = document; + const char *begin = document_.c_str(); + const char *end = begin + document_.length(); + return parse( begin, end, root, collectComments ); +} + + +bool +Reader::parse( std::istream& sin, + Value &root, + bool collectComments ) +{ + //std::istream_iterator begin(sin); + //std::istream_iterator end; + // Those would allow streamed input from a file, if parse() were a + // template function. + + // Since std::string is reference-counted, this at least does not + // create an extra copy. + std::string doc; + std::getline(sin, doc, static_cast(EOF)); + return parse( doc, root, collectComments ); +} + +bool +Reader::parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments ) +{ + if ( !features_.allowComments_ ) + { + collectComments = false; + } + + begin_ = beginDoc; + end_ = endDoc; + collectComments_ = collectComments; + current_ = begin_; + lastValueEnd_ = 0; + lastValue_ = 0; + commentsBefore_ = ""; + errors_.clear(); + while ( !nodes_.empty() ) + nodes_.pop(); + nodes_.push( &root ); + + bool successful = readValue(); + Token token; + skipCommentTokens( token ); + if ( collectComments_ && !commentsBefore_.empty() ) + root.setComment( commentsBefore_, commentAfter ); + if ( features_.strictRoot_ ) + { + if ( !root.isArray() && !root.isObject() ) + { + // Set error location to start of doc, ideally should be first token found in doc + token.type_ = tokenError; + token.start_ = beginDoc; + token.end_ = endDoc; + addError( "A valid JSON document must be either an array or an object value.", + token ); + return false; + } + } + return successful; +} + + +bool +Reader::readValue() +{ + Token token; + skipCommentTokens( token ); + bool successful = true; + + if ( collectComments_ && !commentsBefore_.empty() ) + { + currentValue().setComment( commentsBefore_, commentBefore ); + commentsBefore_ = ""; + } + + + switch ( token.type_ ) + { + case tokenObjectBegin: + successful = readObject( token ); + break; + case tokenArrayBegin: + successful = readArray( token ); + break; + case tokenNumber: + successful = decodeNumber( token ); + break; + case tokenString: + successful = decodeString( token ); + break; + case tokenTrue: + currentValue() = true; + break; + case tokenFalse: + currentValue() = false; + break; + case tokenNull: + currentValue() = Value(); + break; + default: + return addError( "Syntax error: value, object or array expected.", token ); + } + + if ( collectComments_ ) + { + lastValueEnd_ = current_; + lastValue_ = ¤tValue(); + } + + return successful; +} + + +void +Reader::skipCommentTokens( Token &token ) +{ + if ( features_.allowComments_ ) + { + do + { + readToken( token ); + } + while ( token.type_ == tokenComment ); + } + else + { + readToken( token ); + } +} + + +bool +Reader::expectToken( TokenType type, Token &token, const char *message ) +{ + readToken( token ); + if ( token.type_ != type ) + return addError( message, token ); + return true; +} + + +bool +Reader::readToken( Token &token ) +{ + skipSpaces(); + token.start_ = current_; + Char c = getNextChar(); + bool ok = true; + switch ( c ) + { + case '{': + token.type_ = tokenObjectBegin; + break; + case '}': + token.type_ = tokenObjectEnd; + break; + case '[': + token.type_ = tokenArrayBegin; + break; + case ']': + token.type_ = tokenArrayEnd; + break; + case '"': + token.type_ = tokenString; + ok = readString(); + break; + case '/': + token.type_ = tokenComment; + ok = readComment(); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + token.type_ = tokenNumber; + readNumber(); + break; + case 't': + token.type_ = tokenTrue; + ok = match( "rue", 3 ); + break; + case 'f': + token.type_ = tokenFalse; + ok = match( "alse", 4 ); + break; + case 'n': + token.type_ = tokenNull; + ok = match( "ull", 3 ); + break; + case ',': + token.type_ = tokenArraySeparator; + break; + case ':': + token.type_ = tokenMemberSeparator; + break; + case 0: + token.type_ = tokenEndOfStream; + break; + default: + ok = false; + break; + } + if ( !ok ) + token.type_ = tokenError; + token.end_ = current_; + return true; +} + + +void +Reader::skipSpaces() +{ + while ( current_ != end_ ) + { + Char c = *current_; + if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' ) + ++current_; + else + break; + } +} + + +bool +Reader::match( Location pattern, + int patternLength ) +{ + if ( end_ - current_ < patternLength ) + return false; + int index = patternLength; + while ( index-- ) + if ( current_[index] != pattern[index] ) + return false; + current_ += patternLength; + return true; +} + + +bool +Reader::readComment() +{ + Location commentBegin = current_ - 1; + Char c = getNextChar(); + bool successful = false; + if ( c == '*' ) + successful = readCStyleComment(); + else if ( c == '/' ) + successful = readCppStyleComment(); + if ( !successful ) + return false; + + if ( collectComments_ ) + { + CommentPlacement placement = commentBefore; + if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) ) + { + if ( c != '*' || !containsNewLine( commentBegin, current_ ) ) + placement = commentAfterOnSameLine; + } + + addComment( commentBegin, current_, placement ); + } + return true; +} + + +void +Reader::addComment( Location begin, + Location end, + CommentPlacement placement ) +{ + assert( collectComments_ ); + if ( placement == commentAfterOnSameLine ) + { + assert( lastValue_ != 0 ); + lastValue_->setComment( std::string( begin, end ), placement ); + } + else + { + if ( !commentsBefore_.empty() ) + commentsBefore_ += "\n"; + commentsBefore_ += std::string( begin, end ); + } +} + + +bool +Reader::readCStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '*' && *current_ == '/' ) + break; + } + return getNextChar() == '/'; +} + + +bool +Reader::readCppStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '\r' || c == '\n' ) + break; + } + return true; +} + + +void +Reader::readNumber() +{ + while ( current_ != end_ ) + { + if ( !(*current_ >= '0' && *current_ <= '9') && + !in( *current_, '.', 'e', 'E', '+', '-' ) ) + break; + ++current_; + } +} + +bool +Reader::readString() +{ + Char c = 0; + while ( current_ != end_ ) + { + c = getNextChar(); + if ( c == '\\' ) + getNextChar(); + else if ( c == '"' ) + break; + } + return c == '"'; +} + + +bool +Reader::readObject( Token &/*tokenStart*/ ) +{ + Token tokenName; + std::string name; + currentValue() = Value( objectValue ); + while ( readToken( tokenName ) ) + { + bool initialTokenOk = true; + while ( tokenName.type_ == tokenComment && initialTokenOk ) + initialTokenOk = readToken( tokenName ); + if ( !initialTokenOk ) + break; + if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object + return true; + if ( tokenName.type_ != tokenString ) + break; + + name = ""; + if ( !decodeString( tokenName, name ) ) + return recoverFromError( tokenObjectEnd ); + + Token colon; + if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator ) + { + return addErrorAndRecover( "Missing ':' after object member name", + colon, + tokenObjectEnd ); + } + Value &value = currentValue()[ name ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenObjectEnd ); + + Token comma; + if ( !readToken( comma ) + || ( comma.type_ != tokenObjectEnd && + comma.type_ != tokenArraySeparator && + comma.type_ != tokenComment ) ) + { + return addErrorAndRecover( "Missing ',' or '}' in object declaration", + comma, + tokenObjectEnd ); + } + bool finalizeTokenOk = true; + while ( comma.type_ == tokenComment && + finalizeTokenOk ) + finalizeTokenOk = readToken( comma ); + if ( comma.type_ == tokenObjectEnd ) + return true; + } + return addErrorAndRecover( "Missing '}' or object member name", + tokenName, + tokenObjectEnd ); +} + + +bool +Reader::readArray( Token &/*tokenStart*/ ) +{ + currentValue() = Value( arrayValue ); + skipSpaces(); + if ( *current_ == ']' ) // empty array + { + Token endArray; + readToken( endArray ); + return true; + } + int index = 0; + for (;;) + { + Value &value = currentValue()[ index++ ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenArrayEnd ); + + Token token; + // Accept Comment after last item in the array. + ok = readToken( token ); + while ( token.type_ == tokenComment && ok ) + { + ok = readToken( token ); + } + bool badTokenType = ( token.type_ != tokenArraySeparator && + token.type_ != tokenArrayEnd ); + if ( !ok || badTokenType ) + { + return addErrorAndRecover( "Missing ',' or ']' in array declaration", + token, + tokenArrayEnd ); + } + if ( token.type_ == tokenArrayEnd ) + break; + } + return true; +} + + +bool +Reader::decodeNumber( Token &token ) +{ + bool isDouble = false; + for ( Location inspect = token.start_; inspect != token.end_; ++inspect ) + { + isDouble = isDouble + || in( *inspect, '.', 'e', 'E', '+' ) + || ( *inspect == '-' && inspect != token.start_ ); + } + if ( isDouble ) + return decodeDouble( token ); + // Attempts to parse the number as an integer. If the number is + // larger than the maximum supported value of an integer then + // we decode the number as a double. + Location current = token.start_; + bool isNegative = *current == '-'; + if ( isNegative ) + ++current; + Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(-Value::minLargestInt) + : Value::maxLargestUInt; + Value::LargestUInt threshold = maxIntegerValue / 10; + Value::UInt lastDigitThreshold = Value::UInt( maxIntegerValue % 10 ); + assert(/* lastDigitThreshold >=0 &&*/ lastDigitThreshold <= 9 ); + Value::LargestUInt value = 0; + while ( current < token.end_ ) + { + Char c = *current++; + if ( c < '0' || c > '9' ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + Value::UInt digit(c - '0'); + if ( value >= threshold ) + { + // If the current digit is not the last one, or if it is + // greater than the last digit of the maximum integer value, + // the parse the number as a double. + if ( current != token.end_ || digit > lastDigitThreshold ) + { + return decodeDouble( token ); + } + } + value = value * 10 + digit; + } + if ( isNegative ) + currentValue() = -Value::LargestInt( value ); + else if ( value <= Value::LargestUInt(Value::maxInt) ) + currentValue() = Value::LargestInt( value ); + else + currentValue() = value; + return true; +} + + +bool +Reader::decodeDouble( Token &token ) +{ + double value = 0; + const int bufferSize = 32; + int count; + int length = int(token.end_ - token.start_); + if ( length <= bufferSize ) + { + Char buffer[bufferSize+1]; + memcpy( buffer, token.start_, length ); + buffer[length] = 0; + count = sscanf( buffer, "%lf", &value ); + } + else + { + std::string buffer( token.start_, token.end_ ); + count = sscanf( buffer.c_str(), "%lf", &value ); + } + + if ( count != 1 ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + currentValue() = value; + return true; +} + + +bool +Reader::decodeString( Token &token ) +{ + std::string decoded; + if ( !decodeString( token, decoded ) ) + return false; + currentValue() = decoded; + return true; +} + + +bool +Reader::decodeString( Token &token, std::string &decoded ) +{ + decoded.reserve( token.end_ - token.start_ - 2 ); + Location current = token.start_ + 1; // skip '"' + Location end = token.end_ - 1; // do not include '"' + while ( current != end ) + { + Char c = *current++; + if ( c == '"' ) + break; + else if ( c == '\\' ) + { + if ( current == end ) + return addError( "Empty escape sequence in string", token, current ); + Char escape = *current++; + switch ( escape ) + { + case '"': decoded += '"'; break; + case '/': decoded += '/'; break; + case '\\': decoded += '\\'; break; + case 'b': decoded += '\b'; break; + case 'f': decoded += '\f'; break; + case 'n': decoded += '\n'; break; + case 'r': decoded += '\r'; break; + case 't': decoded += '\t'; break; + case 'u': + { + unsigned int unicode; + if ( !decodeUnicodeCodePoint( token, current, end, unicode ) ) + return false; + decoded += codePointToUTF8(unicode); + } + break; + default: + return addError( "Bad escape sequence in string", token, current ); + } + } + else + { + decoded += c; + } + } + return true; +} + +bool +Reader::decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + + if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) ) + return false; + if (unicode >= 0xD800 && unicode <= 0xDBFF) + { + // surrogate pairs + if (end - current < 6) + return addError( "additional six characters expected to parse unicode surrogate pair.", token, current ); + unsigned int surrogatePair; + if (*(current++) == '\\' && *(current++)== 'u') + { + if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair )) + { + unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); + } + else + return false; + } + else + return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current ); + } + return true; +} + +bool +Reader::decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + if ( end - current < 4 ) + return addError( "Bad unicode escape sequence in string: four digits expected.", token, current ); + unicode = 0; + for ( int index =0; index < 4; ++index ) + { + Char c = *current++; + unicode *= 16; + if ( c >= '0' && c <= '9' ) + unicode += c - '0'; + else if ( c >= 'a' && c <= 'f' ) + unicode += c - 'a' + 10; + else if ( c >= 'A' && c <= 'F' ) + unicode += c - 'A' + 10; + else + return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current ); + } + return true; +} + + +bool +Reader::addError( const std::string &message, + Token &token, + Location extra ) +{ + ErrorInfo info; + info.token_ = token; + info.message_ = message; + info.extra_ = extra; + errors_.push_back( info ); + return false; +} + + +bool +Reader::recoverFromError( TokenType skipUntilToken ) +{ + int errorCount = int(errors_.size()); + Token skip; + for (;;) + { + if ( !readToken(skip) ) + errors_.resize( errorCount ); // discard errors caused by recovery + if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream ) + break; + } + errors_.resize( errorCount ); + return false; +} + + +bool +Reader::addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ) +{ + addError( message, token ); + return recoverFromError( skipUntilToken ); +} + + +Value & +Reader::currentValue() +{ + return *(nodes_.top()); +} + + +Reader::Char +Reader::getNextChar() +{ + if ( current_ == end_ ) + return 0; + return *current_++; +} + + +void +Reader::getLocationLineAndColumn( Location location, + int &line, + int &column ) const +{ + Location current = begin_; + Location lastLineStart = current; + line = 0; + while ( current < location && current != end_ ) + { + Char c = *current++; + if ( c == '\r' ) + { + if ( *current == '\n' ) + ++current; + lastLineStart = current; + ++line; + } + else if ( c == '\n' ) + { + lastLineStart = current; + ++line; + } + } + // column & line start at 1 + column = int(location - lastLineStart) + 1; + ++line; +} + + +std::string +Reader::getLocationLineAndColumn( Location location ) const +{ + int line, column; + getLocationLineAndColumn( location, line, column ); + char buffer[18+16+16+1]; + sprintf( buffer, "Line %d, Column %d", line, column ); + return buffer; +} + + +// Deprecated. Preserved for backward compatibility +std::string +Reader::getFormatedErrorMessages() const +{ + return getFormattedErrorMessages(); +} + + +std::string +Reader::getFormattedErrorMessages() const +{ + std::string formattedMessage; + for ( Errors::const_iterator itError = errors_.begin(); + itError != errors_.end(); + ++itError ) + { + const ErrorInfo &error = *itError; + formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n"; + formattedMessage += " " + error.message_ + "\n"; + if ( error.extra_ ) + formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n"; + } + return formattedMessage; +} + + +std::istream& operator>>( std::istream &sin, Value &root ) +{ + Json::Reader reader; + bool ok = reader.parse(sin, root, true); + //JSON_ASSERT( ok ); + if (!ok) throw std::runtime_error(reader.getFormattedErrorMessages()); + return sin; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_reader.cpp +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_batchallocator.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED +# define JSONCPP_BATCHALLOCATOR_H_INCLUDED + +# include +# include + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + +namespace Json { + +/* Fast memory allocator. + * + * This memory allocator allocates memory for a batch of object (specified by + * the page size, the number of object in each page). + * + * It does not allow the destruction of a single object. All the allocated objects + * can be destroyed at once. The memory can be either released or reused for future + * allocation. + * + * The in-place new operator must be used to construct the object using the pointer + * returned by allocate. + */ +template +class BatchAllocator +{ +public: + typedef AllocatedType Type; + + BatchAllocator( unsigned int objectsPerPage = 255 ) + : freeHead_( 0 ) + , objectsPerPage_( objectsPerPage ) + { +// printf( "Size: %d => %s\n", sizeof(AllocatedType), typeid(AllocatedType).name() ); + assert( sizeof(AllocatedType) * objectPerAllocation >= sizeof(AllocatedType *) ); // We must be able to store a slist in the object free space. + assert( objectsPerPage >= 16 ); + batches_ = allocateBatch( 0 ); // allocated a dummy page + currentBatch_ = batches_; + } + + ~BatchAllocator() + { + for ( BatchInfo *batch = batches_; batch; ) + { + BatchInfo *nextBatch = batch->next_; + free( batch ); + batch = nextBatch; + } + } + + /// allocate space for an array of objectPerAllocation object. + /// @warning it is the responsability of the caller to call objects constructors. + AllocatedType *allocate() + { + if ( freeHead_ ) // returns node from free list. + { + AllocatedType *object = freeHead_; + freeHead_ = *static_cast(object); + return object; + } + if ( currentBatch_->used_ == currentBatch_->end_ ) + { + currentBatch_ = currentBatch_->next_; + while ( currentBatch_ && currentBatch_->used_ == currentBatch_->end_ ) + currentBatch_ = currentBatch_->next_; + + if ( !currentBatch_ ) // no free batch found, allocate a new one + { + currentBatch_ = allocateBatch( objectsPerPage_ ); + currentBatch_->next_ = batches_; // insert at the head of the list + batches_ = currentBatch_; + } + } + AllocatedType *allocated = currentBatch_->used_; + currentBatch_->used_ += objectPerAllocation; + return allocated; + } + + /// Release the object. + /// @warning it is the responsability of the caller to actually destruct the object. + void release( AllocatedType *object ) + { + assert( object != 0 ); + *static_cast(object) = freeHead_; + freeHead_ = object; + } + +private: + struct BatchInfo + { + BatchInfo *next_; + AllocatedType *used_; + AllocatedType *end_; + AllocatedType buffer_[objectPerAllocation]; + }; + + // disabled copy constructor and assignement operator. + BatchAllocator( const BatchAllocator & ); + void operator =( const BatchAllocator &); + + static BatchInfo *allocateBatch( unsigned int objectsPerPage ) + { + const unsigned int mallocSize = sizeof(BatchInfo) - sizeof(AllocatedType)* objectPerAllocation + + sizeof(AllocatedType) * objectPerAllocation * objectsPerPage; + BatchInfo *batch = static_cast( malloc( mallocSize ) ); + batch->next_ = 0; + batch->used_ = batch->buffer_; + batch->end_ = batch->buffer_ + objectsPerPage; + return batch; + } + + BatchInfo *batches_; + BatchInfo *currentBatch_; + /// Head of a single linked list within the allocated space of freeed object + AllocatedType *freeHead_; + unsigned int objectsPerPage_; +}; + + +} // namespace Json + +# endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION + +#endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED + + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_batchallocator.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_valueiterator.inl +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +// included by json_value.cpp + +namespace Json { + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIteratorBase +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIteratorBase::ValueIteratorBase() +#ifndef JSON_VALUE_USE_INTERNAL_MAP + : current_() + , isNull_( true ) +{ +} +#else + : isArray_( true ) + , isNull_( true ) +{ + iterator_.array_ = ValueInternalArray::IteratorState(); +} +#endif + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIteratorBase::ValueIteratorBase( const Value::ObjectValues::iterator ¤t ) + : current_( current ) + , isNull_( false ) +{ +} +#else +ValueIteratorBase::ValueIteratorBase( const ValueInternalArray::IteratorState &state ) + : isArray_( true ) +{ + iterator_.array_ = state; +} + + +ValueIteratorBase::ValueIteratorBase( const ValueInternalMap::IteratorState &state ) + : isArray_( false ) +{ + iterator_.map_ = state; +} +#endif + +Value & +ValueIteratorBase::deref() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + return current_->second; +#else + if ( isArray_ ) + return ValueInternalArray::dereference( iterator_.array_ ); + return ValueInternalMap::value( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::increment() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ++current_; +#else + if ( isArray_ ) + ValueInternalArray::increment( iterator_.array_ ); + ValueInternalMap::increment( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::decrement() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + --current_; +#else + if ( isArray_ ) + ValueInternalArray::decrement( iterator_.array_ ); + ValueInternalMap::decrement( iterator_.map_ ); +#endif +} + + +ValueIteratorBase::difference_type +ValueIteratorBase::computeDistance( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP +# ifdef JSON_USE_CPPTL_SMALLMAP + return current_ - other.current_; +# else + // Iterator for null value are initialized using the default + // constructor, which initialize current_ to the default + // std::map::iterator. As begin() and end() are two instance + // of the default std::map::iterator, they can not be compared. + // To allow this, we handle this comparison specifically. + if ( isNull_ && other.isNull_ ) + { + return 0; + } + + + // Usage of std::distance is not portable (does not compile with Sun Studio 12 RogueWave STL, + // which is the one used by default). + // Using a portable hand-made version for non random iterator instead: + // return difference_type( std::distance( current_, other.current_ ) ); + difference_type myDistance = 0; + for ( Value::ObjectValues::iterator it = current_; it != other.current_; ++it ) + { + ++myDistance; + } + return myDistance; +# endif +#else + if ( isArray_ ) + return ValueInternalArray::distance( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::distance( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +bool +ValueIteratorBase::isEqual( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + if ( isNull_ ) + { + return other.isNull_; + } + return current_ == other.current_; +#else + if ( isArray_ ) + return ValueInternalArray::equals( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::equals( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::copy( const SelfType &other ) +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + current_ = other.current_; +#else + if ( isArray_ ) + iterator_.array_ = other.iterator_.array_; + iterator_.map_ = other.iterator_.map_; +#endif +} + + +Value +ValueIteratorBase::key() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( czstring.c_str() ) + { + if ( czstring.isStaticString() ) + return Value( StaticString( czstring.c_str() ) ); + return Value( czstring.c_str() ); + } + return Value( czstring.index() ); +#else + if ( isArray_ ) + return Value( ValueInternalArray::indexOf( iterator_.array_ ) ); + bool isStatic; + const char *memberName = ValueInternalMap::key( iterator_.map_, isStatic ); + if ( isStatic ) + return Value( StaticString( memberName ) ); + return Value( memberName ); +#endif +} + + +UInt +ValueIteratorBase::index() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( !czstring.c_str() ) + return czstring.index(); + return Value::UInt( -1 ); +#else + if ( isArray_ ) + return Value::UInt( ValueInternalArray::indexOf( iterator_.array_ ) ); + return Value::UInt( -1 ); +#endif +} + + +const char * +ValueIteratorBase::memberName() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const char *name = (*current_).first.c_str(); + return name ? name : ""; +#else + if ( !isArray_ ) + return ValueInternalMap::key( iterator_.map_ ); + return ""; +#endif +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueConstIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueConstIterator::ValueConstIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueConstIterator::ValueConstIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueConstIterator::ValueConstIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueConstIterator::ValueConstIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueConstIterator & +ValueConstIterator::operator =( const ValueIteratorBase &other ) +{ + copy( other ); + return *this; +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIterator::ValueIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIterator::ValueIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueIterator::ValueIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueIterator::ValueIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueIterator::ValueIterator( const ValueConstIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator::ValueIterator( const ValueIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator & +ValueIterator::operator =( const SelfType &other ) +{ + copy( other ); + return *this; +} + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_valueiterator.inl +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_value.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include +# ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +# include "json_batchallocator.h" +# endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#ifdef JSON_USE_CPPTL +# include +#endif +#include // size_t + +#define JSON_ASSERT_UNREACHABLE assert( false ) +#define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw +#define JSON_FAIL_MESSAGE( message ) throw std::runtime_error( message ); +#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) JSON_FAIL_MESSAGE( message ) + +namespace Json { + +const Value Value::null; +const Int Value::minInt = Int( ~(UInt(-1)/2) ); +const Int Value::maxInt = Int( UInt(-1)/2 ); +const UInt Value::maxUInt = UInt(-1); +const Int64 Value::minInt64 = Int64( ~(UInt64(-1)/2) ); +const Int64 Value::maxInt64 = Int64( UInt64(-1)/2 ); +const UInt64 Value::maxUInt64 = UInt64(-1); +const LargestInt Value::minLargestInt = LargestInt( ~(LargestUInt(-1)/2) ); +const LargestInt Value::maxLargestInt = LargestInt( LargestUInt(-1)/2 ); +const LargestUInt Value::maxLargestUInt = LargestUInt(-1); + + +/// Unknown size marker +static const unsigned int unknown = -1; + + +/** Duplicates the specified string value. + * @param value Pointer to the string to duplicate. Must be zero-terminated if + * length is "unknown". + * @param length Length of the value. if equals to unknown, then it will be + * computed using strlen(value). + * @return Pointer on the duplicate instance of string. + */ +static inline char * +duplicateStringValue( const char *value, + unsigned int length = unknown ) +{ + if ( length == unknown ) + length = static_cast(strlen(value)); + char *newString = static_cast( malloc( length + 1 ) ); + JSON_ASSERT_MESSAGE( newString != 0, "Failed to allocate string value buffer" ); + memcpy( newString, value, length ); + newString[length] = 0; + return newString; +} + + +/** Free the string duplicated by duplicateStringValue(). + */ +static inline void +releaseStringValue( char *value ) +{ + if ( value ) + free( value ); +} + +} // namespace Json + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ValueInternals... +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +#if !defined(JSON_IS_AMALGAMATION) +# ifdef JSON_VALUE_USE_INTERNAL_MAP +# include "json_internalarray.inl" +# include "json_internalmap.inl" +# endif // JSON_VALUE_USE_INTERNAL_MAP + +# include "json_valueiterator.inl" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CommentInfo +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + + +Value::CommentInfo::CommentInfo() + : comment_( 0 ) +{ +} + +Value::CommentInfo::~CommentInfo() +{ + if ( comment_ ) + releaseStringValue( comment_ ); +} + + +void +Value::CommentInfo::setComment( const char *text ) +{ + if ( comment_ ) + releaseStringValue( comment_ ); + JSON_ASSERT( text != 0 ); + JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /"); + // It seems that /**/ style comments are acceptable as well. + comment_ = duplicateStringValue( text ); +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CZString +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +# ifndef JSON_VALUE_USE_INTERNAL_MAP + +// Notes: index_ indicates if the string was allocated when +// a string is stored. + +Value::CZString::CZString( ArrayIndex index ) + : cstr_( 0 ) + , index_( index ) +{ +} + +Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate ) + : cstr_( allocate == duplicate ? duplicateStringValue(cstr) + : cstr ) + , index_( allocate ) +{ +} + +Value::CZString::CZString( const CZString &other ) +: cstr_( other.index_ != noDuplication && other.cstr_ != 0 + ? duplicateStringValue( other.cstr_ ) + : other.cstr_ ) + , index_( other.cstr_ ? (other.index_ == noDuplication ? static_cast(noDuplication) : static_cast(duplicate)) + : other.index_ ) +{ +} + +Value::CZString::~CZString() +{ + if ( cstr_ && index_ == duplicate ) + releaseStringValue( const_cast( cstr_ ) ); +} + +void +Value::CZString::swap( CZString &other ) +{ + std::swap( cstr_, other.cstr_ ); + std::swap( index_, other.index_ ); +} + +Value::CZString & +Value::CZString::operator =( const CZString &other ) +{ + CZString temp( other ); + swap( temp ); + return *this; +} + +bool +Value::CZString::operator<( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) < 0; + return index_ < other.index_; +} + +bool +Value::CZString::operator==( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) == 0; + return index_ == other.index_; +} + + +ArrayIndex +Value::CZString::index() const +{ + return index_; +} + + +const char * +Value::CZString::c_str() const +{ + return cstr_; +} + +bool +Value::CZString::isStaticString() const +{ + return index_ == noDuplication; +} + +#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::Value +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +/*! \internal Default constructor initialization must be equivalent to: + * memset( this, 0, sizeof(Value) ) + * This optimization is used in ValueInternalMap fast allocator. + */ +Value::Value( ValueType type ) + : type_( type ) + , allocated_( 0 ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type ) + { + case nullValue: + break; + case intValue: + case uintValue: + value_.int_ = 0; + break; + case realValue: + value_.real_ = 0.0; + break; + case stringValue: + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues(); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArray(); + break; + case objectValue: + value_.map_ = mapAllocator()->newMap(); + break; +#endif + case booleanValue: + value_.bool_ = false; + break; + default: + JSON_ASSERT_UNREACHABLE; + } +} + + +#if defined(JSON_HAS_INT64) +Value::Value( UInt value ) + : type_( uintValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.uint_ = value; +} + +Value::Value( Int value ) + : type_( intValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.int_ = value; +} + +#endif // if defined(JSON_HAS_INT64) + + +Value::Value( Int64 value ) + : type_( intValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.int_ = value; +} + + +Value::Value( UInt64 value ) + : type_( uintValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.uint_ = value; +} + +Value::Value( double value ) + : type_( realValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.real_ = value; +} + +Value::Value( const char *value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value ); +} + + +Value::Value( const char *beginValue, + const char *endValue ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( beginValue, + static_cast(endValue - beginValue) ); +} + + +Value::Value( const std::string &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value.c_str(), + static_cast(value.length()) ); + +} + +Value::Value( const StaticString &value ) + : type_( stringValue ) + , allocated_( false ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = const_cast( value.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +Value::Value( const CppTL::ConstString &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = duplicateStringValue( value, value.length() ); +} +# endif + +Value::Value( bool value ) + : type_( booleanValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.bool_ = value; +} + + +Value::Value( const Value &other ) + : type_( other.type_ ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + value_ = other.value_; + break; + case stringValue: + if ( other.value_.string_ ) + { + value_.string_ = duplicateStringValue( other.value_.string_ ); + allocated_ = true; + } + else + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues( *other.value_.map_ ); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArrayCopy( *other.value_.array_ ); + break; + case objectValue: + value_.map_ = mapAllocator()->newMapCopy( *other.value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + if ( other.comments_ ) + { + comments_ = new CommentInfo[numberOfCommentPlacement]; + for ( int comment =0; comment < numberOfCommentPlacement; ++comment ) + { + const CommentInfo &otherComment = other.comments_[comment]; + if ( otherComment.comment_ ) + comments_[comment].setComment( otherComment.comment_ ); + } + } +} + + +Value::~Value() +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + break; + case stringValue: + if ( allocated_ ) + releaseStringValue( value_.string_ ); + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + delete value_.map_; + break; +#else + case arrayValue: + arrayAllocator()->destructArray( value_.array_ ); + break; + case objectValue: + mapAllocator()->destructMap( value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + + if ( comments_ ) + delete[] comments_; +} + +Value & +Value::operator=( const Value &other ) +{ + Value temp( other ); + swap( temp ); + return *this; +} + +void +Value::swap( Value &other ) +{ + ValueType temp = type_; + type_ = other.type_; + other.type_ = temp; + std::swap( value_, other.value_ ); + int temp2 = allocated_; + allocated_ = other.allocated_; + other.allocated_ = temp2; +} + +ValueType +Value::type() const +{ + return type_; +} + + +int +Value::compare( const Value &other ) const +{ + if ( *this < other ) + return -1; + if ( *this > other ) + return 1; + return 0; +} + + +bool +Value::operator <( const Value &other ) const +{ + int typeDelta = type_ - other.type_; + if ( typeDelta ) + return typeDelta < 0 ? true : false; + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + return value_.int_ < other.value_.int_; + case uintValue: + return value_.uint_ < other.value_.uint_; + case realValue: + return value_.real_ < other.value_.real_; + case booleanValue: + return value_.bool_ < other.value_.bool_; + case stringValue: + return ( value_.string_ == 0 && other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) < 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + { + int delta = int( value_.map_->size() - other.value_.map_->size() ); + if ( delta ) + return delta < 0; + return (*value_.map_) < (*other.value_.map_); + } +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) < 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) < 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable +} + +bool +Value::operator <=( const Value &other ) const +{ + return !(other < *this); +} + +bool +Value::operator >=( const Value &other ) const +{ + return !(*this < other); +} + +bool +Value::operator >( const Value &other ) const +{ + return other < *this; +} + +bool +Value::operator ==( const Value &other ) const +{ + //if ( type_ != other.type_ ) + // GCC 2.95.3 says: + // attempt to take address of bit-field structure member `Json::Value::type_' + // Beats me, but a temp solves the problem. + int temp = other.type_; + if ( type_ != temp ) + return false; + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return value_.int_ == other.value_.int_; + case uintValue: + return value_.uint_ == other.value_.uint_; + case realValue: + return value_.real_ == other.value_.real_; + case booleanValue: + return value_.bool_ == other.value_.bool_; + case stringValue: + return ( value_.string_ == other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) == 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + return value_.map_->size() == other.value_.map_->size() + && (*value_.map_) == (*other.value_.map_); +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) == 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) == 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable +} + +bool +Value::operator !=( const Value &other ) const +{ + return !( *this == other ); +} + +const char * +Value::asCString() const +{ + JSON_ASSERT( type_ == stringValue ); + return value_.string_; +} + + +std::string +Value::asString() const +{ + switch ( type_ ) + { + case nullValue: + return ""; + case stringValue: + return value_.string_ ? value_.string_ : ""; + case booleanValue: + return value_.bool_ ? "true" : "false"; + case intValue: + case uintValue: + case realValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to string" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return ""; // unreachable +} + +# ifdef JSON_USE_CPPTL +CppTL::ConstString +Value::asConstString() const +{ + return CppTL::ConstString( asString().c_str() ); +} +# endif + + +Value::Int +Value::asInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= minInt && value_.int_ <= maxInt, "unsigned integer out of signed int range" ); + return Int(value_.int_); + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= UInt(maxInt), "unsigned integer out of signed int range" ); + return Int(value_.uint_); + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" ); + return Int( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to int" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +Value::UInt +Value::asUInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" ); + JSON_ASSERT_MESSAGE( value_.int_ <= maxUInt, "signed integer out of UInt range" ); + return UInt(value_.int_); + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= maxUInt, "unsigned integer out of UInt range" ); + return UInt(value_.uint_); + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" ); + return UInt( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to uint" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +# if defined(JSON_HAS_INT64) + +Value::Int64 +Value::asInt64() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + return value_.int_; + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ <= UInt64(maxInt64), "unsigned integer out of Int64 range" ); + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= minInt64 && value_.real_ <= maxInt64, "Real out of Int64 range" ); + return Int( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to Int64" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +Value::UInt64 +Value::asUInt64() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to UInt64" ); + return value_.int_; + case uintValue: + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt64, "Real out of UInt64 range" ); + return UInt( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to UInt64" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} +# endif // if defined(JSON_HAS_INT64) + + +LargestInt +Value::asLargestInt() const +{ +#if defined(JSON_NO_INT64) + return asInt(); +#else + return asInt64(); +#endif +} + + +LargestUInt +Value::asLargestUInt() const +{ +#if defined(JSON_NO_INT64) + return asUInt(); +#else + return asUInt64(); +#endif +} + + +double +Value::asDouble() const +{ + switch ( type_ ) + { + case nullValue: + return 0.0; + case intValue: + return static_cast( value_.int_ ); + case uintValue: +#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( value_.uint_ ); +#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); +#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + case realValue: + return value_.real_; + case booleanValue: + return value_.bool_ ? 1.0 : 0.0; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to double" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + +float +Value::asFloat() const +{ + switch ( type_ ) + { + case nullValue: + return 0.0f; + case intValue: + return static_cast( value_.int_ ); + case uintValue: +#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( value_.uint_ ); +#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); +#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + case realValue: + return static_cast( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1.0f : 0.0f; + case stringValue: + case arrayValue: + case objectValue: + JSON_FAIL_MESSAGE( "Type is not convertible to float" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0.0f; // unreachable; +} + +bool +Value::asBool() const +{ + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + case uintValue: + return value_.int_ != 0; + case realValue: + return value_.real_ != 0.0; + case booleanValue: + return value_.bool_; + case stringValue: + return value_.string_ && value_.string_[0] != 0; + case arrayValue: + case objectValue: + return value_.map_->size() != 0; + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +bool +Value::isConvertibleTo( ValueType other ) const +{ + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return ( other == nullValue && value_.int_ == 0 ) + || other == intValue + || ( other == uintValue && value_.int_ >= 0 ) + || other == realValue + || other == stringValue + || other == booleanValue; + case uintValue: + return ( other == nullValue && value_.uint_ == 0 ) + || ( other == intValue && value_.uint_ <= static_cast(maxInt) ) + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case realValue: + return ( other == nullValue && value_.real_ == 0.0 ) + || ( other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt ) + || ( other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt ) + || other == realValue + || other == stringValue + || other == booleanValue; + case booleanValue: + return ( other == nullValue && value_.bool_ == false ) + || other == intValue + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case stringValue: + return other == stringValue + || ( other == nullValue && (!value_.string_ || value_.string_[0] == 0) ); + case arrayValue: + return other == arrayValue + || ( other == nullValue && value_.map_->size() == 0 ); + case objectValue: + return other == objectValue + || ( other == nullValue && value_.map_->size() == 0 ); + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +/// Number of values in array or object +ArrayIndex +Value::size() const +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + case stringValue: + return 0; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: // size of the array is highest index + 1 + if ( !value_.map_->empty() ) + { + ObjectValues::const_iterator itLast = value_.map_->end(); + --itLast; + return (*itLast).first.index()+1; + } + return 0; + case objectValue: + return ArrayIndex( value_.map_->size() ); +#else + case arrayValue: + return Int( value_.array_->size() ); + case objectValue: + return Int( value_.map_->size() ); +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +bool +Value::empty() const +{ + if ( isNull() || isArray() || isObject() ) + return size() == 0u; + else + return false; +} + + +bool +Value::operator!() const +{ + return isNull(); +} + + +void +Value::clear() +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue ); + + switch ( type_ ) + { +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_->clear(); + break; +#else + case arrayValue: + value_.array_->clear(); + break; + case objectValue: + value_.map_->clear(); + break; +#endif + default: + break; + } +} + +void +Value::resize( ArrayIndex newSize ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ArrayIndex oldSize = size(); + if ( newSize == 0 ) + clear(); + else if ( newSize > oldSize ) + (*this)[ newSize - 1 ]; + else + { + for ( ArrayIndex index = newSize; index < oldSize; ++index ) + { + value_.map_->erase( index ); + } + assert( size() == newSize ); + } +#else + value_.array_->resize( newSize ); +#endif +} + + +Value & +Value::operator[]( ArrayIndex index ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::iterator it = value_.map_->lower_bound( key ); + if ( it != value_.map_->end() && (*it).first == key ) + return (*it).second; + + ObjectValues::value_type defaultValue( key, null ); + it = value_.map_->insert( it, defaultValue ); + return (*it).second; +#else + return value_.array_->resolveReference( index ); +#endif +} + + +Value & +Value::operator[]( int index ) +{ + JSON_ASSERT( index >= 0 ); + return (*this)[ ArrayIndex(index) ]; +} + + +const Value & +Value::operator[]( ArrayIndex index ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::const_iterator it = value_.map_->find( key ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + Value *value = value_.array_->find( index ); + return value ? *value : null; +#endif +} + + +const Value & +Value::operator[]( int index ) const +{ + JSON_ASSERT( index >= 0 ); + return (*this)[ ArrayIndex(index) ]; +} + + +Value & +Value::operator[]( const char *key ) +{ + return resolveReference( key, false ); +} + + +Value & +Value::resolveReference( const char *key, + bool isStatic ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + *this = Value( objectValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, isStatic ? CZString::noDuplication + : CZString::duplicateOnCopy ); + ObjectValues::iterator it = value_.map_->lower_bound( actualKey ); + if ( it != value_.map_->end() && (*it).first == actualKey ) + return (*it).second; + + ObjectValues::value_type defaultValue( actualKey, null ); + it = value_.map_->insert( it, defaultValue ); + Value &value = (*it).second; + return value; +#else + return value_.map_->resolveReference( key, isStatic ); +#endif +} + + +Value +Value::get( ArrayIndex index, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[index]); + return value == &null ? defaultValue : *value; +} + + +bool +Value::isValidIndex( ArrayIndex index ) const +{ + return index < size(); +} + + + +const Value & +Value::operator[]( const char *key ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::const_iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + const Value *value = value_.map_->find( key ); + return value ? *value : null; +#endif +} + + +Value & +Value::operator[]( const std::string &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const std::string &key ) const +{ + return (*this)[ key.c_str() ]; +} + +Value & +Value::operator[]( const StaticString &key ) +{ + return resolveReference( key, true ); +} + + +# ifdef JSON_USE_CPPTL +Value & +Value::operator[]( const CppTL::ConstString &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const CppTL::ConstString &key ) const +{ + return (*this)[ key.c_str() ]; +} +# endif + + +Value & +Value::append( const Value &value ) +{ + return (*this)[size()] = value; +} + + +Value +Value::get( const char *key, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[key]); + return value == &null ? defaultValue : *value; +} + + +Value +Value::get( const std::string &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} + +Value +Value::removeMember( const char* key ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + Value old(it->second); + value_.map_->erase(it); + return old; +#else + Value *value = value_.map_->find( key ); + if (value){ + Value old(*value); + value_.map_.remove( key ); + return old; + } else { + return null; + } +#endif +} + +Value +Value::removeMember( const std::string &key ) +{ + return removeMember( key.c_str() ); +} + +# ifdef JSON_USE_CPPTL +Value +Value::get( const CppTL::ConstString &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} +# endif + +bool +Value::isMember( const char *key ) const +{ + const Value *value = &((*this)[key]); + return value != &null; +} + + +bool +Value::isMember( const std::string &key ) const +{ + return isMember( key.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +bool +Value::isMember( const CppTL::ConstString &key ) const +{ + return isMember( key.c_str() ); +} +#endif + +Value::Members +Value::getMemberNames() const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return Value::Members(); + Members members; + members.reserve( value_.map_->size() ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ObjectValues::const_iterator it = value_.map_->begin(); + ObjectValues::const_iterator itEnd = value_.map_->end(); + for ( ; it != itEnd; ++it ) + members.push_back( std::string( (*it).first.c_str() ) ); +#else + ValueInternalMap::IteratorState it; + ValueInternalMap::IteratorState itEnd; + value_.map_->makeBeginIterator( it ); + value_.map_->makeEndIterator( itEnd ); + for ( ; !ValueInternalMap::equals( it, itEnd ); ValueInternalMap::increment(it) ) + members.push_back( std::string( ValueInternalMap::key( it ) ) ); +#endif + return members; +} +// +//# ifdef JSON_USE_CPPTL +//EnumMemberNames +//Value::enumMemberNames() const +//{ +// if ( type_ == objectValue ) +// { +// return CppTL::Enum::any( CppTL::Enum::transform( +// CppTL::Enum::keys( *(value_.map_), CppTL::Type() ), +// MemberNamesTransform() ) ); +// } +// return EnumMemberNames(); +//} +// +// +//EnumValues +//Value::enumValues() const +//{ +// if ( type_ == objectValue || type_ == arrayValue ) +// return CppTL::Enum::anyValues( *(value_.map_), +// CppTL::Type() ); +// return EnumValues(); +//} +// +//# endif + + +bool +Value::isNull() const +{ + return type_ == nullValue; +} + + +bool +Value::isBool() const +{ + return type_ == booleanValue; +} + + +bool +Value::isInt() const +{ + return type_ == intValue; +} + + +bool +Value::isUInt() const +{ + return type_ == uintValue; +} + + +bool +Value::isIntegral() const +{ + return type_ == intValue + || type_ == uintValue + || type_ == booleanValue; +} + + +bool +Value::isDouble() const +{ + return type_ == realValue; +} + + +bool +Value::isNumeric() const +{ + return isIntegral() || isDouble(); +} + + +bool +Value::isString() const +{ + return type_ == stringValue; +} + + +bool +Value::isArray() const +{ + return type_ == nullValue || type_ == arrayValue; +} + + +bool +Value::isObject() const +{ + return type_ == nullValue || type_ == objectValue; +} + + +void +Value::setComment( const char *comment, + CommentPlacement placement ) +{ + if ( !comments_ ) + comments_ = new CommentInfo[numberOfCommentPlacement]; + comments_[placement].setComment( comment ); +} + + +void +Value::setComment( const std::string &comment, + CommentPlacement placement ) +{ + setComment( comment.c_str(), placement ); +} + + +bool +Value::hasComment( CommentPlacement placement ) const +{ + return comments_ != 0 && comments_[placement].comment_ != 0; +} + +std::string +Value::getComment( CommentPlacement placement ) const +{ + if ( hasComment(placement) ) + return comments_[placement].comment_; + return ""; +} + + +std::string +Value::toStyledString() const +{ + StyledWriter writer; + return writer.write( *this ); +} + + +Value::const_iterator +Value::begin() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + +Value::const_iterator +Value::end() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + + +Value::iterator +Value::begin() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return iterator(); +} + +Value::iterator +Value::end() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return iterator(); +} + + +// class PathArgument +// ////////////////////////////////////////////////////////////////// + +PathArgument::PathArgument() + : kind_( kindNone ) +{ +} + + +PathArgument::PathArgument( ArrayIndex index ) + : index_( index ) + , kind_( kindIndex ) +{ +} + + +PathArgument::PathArgument( const char *key ) + : key_( key ) + , kind_( kindKey ) +{ +} + + +PathArgument::PathArgument( const std::string &key ) + : key_( key.c_str() ) + , kind_( kindKey ) +{ +} + +// class Path +// ////////////////////////////////////////////////////////////////// + +Path::Path( const std::string &path, + const PathArgument &a1, + const PathArgument &a2, + const PathArgument &a3, + const PathArgument &a4, + const PathArgument &a5 ) +{ + InArgs in; + in.push_back( &a1 ); + in.push_back( &a2 ); + in.push_back( &a3 ); + in.push_back( &a4 ); + in.push_back( &a5 ); + makePath( path, in ); +} + + +void +Path::makePath( const std::string &path, + const InArgs &in ) +{ + const char *current = path.c_str(); + const char *end = current + path.length(); + InArgs::const_iterator itInArg = in.begin(); + while ( current != end ) + { + if ( *current == '[' ) + { + ++current; + if ( *current == '%' ) + addPathInArg( path, in, itInArg, PathArgument::kindIndex ); + else + { + ArrayIndex index = 0; + for ( ; current != end && *current >= '0' && *current <= '9'; ++current ) + index = index * 10 + ArrayIndex(*current - '0'); + args_.push_back( index ); + } + if ( current == end || *current++ != ']' ) + invalidPath( path, int(current - path.c_str()) ); + } + else if ( *current == '%' ) + { + addPathInArg( path, in, itInArg, PathArgument::kindKey ); + ++current; + } + else if ( *current == '.' ) + { + ++current; + } + else + { + const char *beginName = current; + while ( current != end && !strchr( "[.", *current ) ) + ++current; + args_.push_back( std::string( beginName, current ) ); + } + } +} + + +void +Path::addPathInArg( const std::string &/*path*/, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ) +{ + if ( itInArg == in.end() ) + { + // Error: missing argument %d + } + else if ( (*itInArg)->kind_ != kind ) + { + // Error: bad argument type + } + else + { + args_.push_back( **itInArg ); + } +} + + +void +Path::invalidPath( const std::string &/*path*/, + int /*location*/ ) +{ + // Error: invalid path. +} + + +const Value & +Path::resolve( const Value &root ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + { + // Error: unable to resolve path (array value expected at position... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: unable to resolve path (object value expected at position...) + } + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + { + // Error: unable to resolve path (object has no member named '' at position...) + } + } + } + return *node; +} + + +Value +Path::resolve( const Value &root, + const Value &defaultValue ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + return defaultValue; + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + return defaultValue; + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + return defaultValue; + } + } + return *node; +} + + +Value & +Path::make( Value &root ) const +{ + Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() ) + { + // Error: node is not an array at position ... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: node is not an object at position... + } + node = &((*node)[arg.key_]); + } + } + return *node; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_value.cpp +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: src/lib_json/json_writer.cpp +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#if !defined(JSON_IS_AMALGAMATION) +# include +# include "json_tool.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include +#include +#include + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +static bool containsControlCharacter( const char* str ) +{ + while ( *str ) + { + if ( isControlCharacter( *(str++) ) ) + return true; + } + return false; +} + + +std::string valueToString( LargestInt value ) +{ + UIntToStringBuffer buffer; + char *current = buffer + sizeof(buffer); + bool isNegative = value < 0; + if ( isNegative ) + value = -value; + uintToString( LargestUInt(value), current ); + if ( isNegative ) + *--current = '-'; + assert( current >= buffer ); + return current; +} + + +std::string valueToString( LargestUInt value ) +{ + UIntToStringBuffer buffer; + char *current = buffer + sizeof(buffer); + uintToString( value, current ); + assert( current >= buffer ); + return current; +} + +#if defined(JSON_HAS_INT64) + +std::string valueToString( Int value ) +{ + return valueToString( LargestInt(value) ); +} + + +std::string valueToString( UInt value ) +{ + return valueToString( LargestUInt(value) ); +} + +#endif // # if defined(JSON_HAS_INT64) + + +std::string valueToString( double value ) +{ + char buffer[32]; +#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 to avoid warning. + sprintf_s(buffer, sizeof(buffer), "%#.16g", value); +#else + sprintf(buffer, "%#.16g", value); +#endif + char* ch = buffer + strlen(buffer) - 1; + if (*ch != '0') return buffer; // nothing to truncate, so save time + while(ch > buffer && *ch == '0'){ + --ch; + } + char* last_nonzero = ch; + while(ch >= buffer){ + switch(*ch){ + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + --ch; + continue; + case '.': + // Truncate zeroes to save bytes in output, but keep one. + *(last_nonzero+2) = '\0'; + return buffer; + default: + return buffer; + } + } + return buffer; +} + + +std::string valueToString( bool value ) +{ + return value ? "true" : "false"; +} + +std::string valueToQuotedString( const char *value ) +{ + // Not sure how to handle unicode... + if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && !containsControlCharacter( value )) + return std::string("\"") + value + "\""; + // We have to walk value and escape any special characters. + // Appending to std::string is not efficient, but this should be rare. + // (Note: forward slashes are *not* rare, but I am not escaping them.) + std::string::size_type maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL + std::string result; + result.reserve(maxsize); // to avoid lots of mallocs + result += "\""; + for (const char* c=value; *c != 0; ++c) + { + switch(*c) + { + case '\"': + result += "\\\""; + break; + case '\\': + result += "\\\\"; + break; + case '\b': + result += "\\b"; + break; + case '\f': + result += "\\f"; + break; + case '\n': + result += "\\n"; + break; + case '\r': + result += "\\r"; + break; + case '\t': + result += "\\t"; + break; + //case '/': + // Even though \/ is considered a legal escape in JSON, a bare + // slash is also legal, so I see no reason to escape it. + // (I hope I am not misunderstanding something. + // blep notes: actually escaping \/ may be useful in javascript to avoid (*c); + result += oss.str(); + } + else + { + result += *c; + } + break; + } + } + result += "\""; + return result; +} + +// Class Writer +// ////////////////////////////////////////////////////////////////// +Writer::~Writer() +{ +} + + +// Class FastWriter +// ////////////////////////////////////////////////////////////////// + +FastWriter::FastWriter() + : yamlCompatiblityEnabled_( false ) +{ +} + + +void +FastWriter::enableYAMLCompatibility() +{ + yamlCompatiblityEnabled_ = true; +} + + +std::string +FastWriter::write( const Value &root ) +{ + document_ = ""; + writeValue( root ); + document_ += "\n"; + return document_; +} + + +void +FastWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + document_ += "null"; + break; + case intValue: + document_ += valueToString( value.asLargestInt() ); + break; + case uintValue: + document_ += valueToString( value.asLargestUInt() ); + break; + case realValue: + document_ += valueToString( value.asDouble() ); + break; + case stringValue: + document_ += valueToQuotedString( value.asCString() ); + break; + case booleanValue: + document_ += valueToString( value.asBool() ); + break; + case arrayValue: + { + document_ += "["; + int size = value.size(); + for ( int index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ","; + writeValue( value[index] ); + } + document_ += "]"; + } + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + document_ += "{"; + for ( Value::Members::iterator it = members.begin(); + it != members.end(); + ++it ) + { + const std::string &name = *it; + if ( it != members.begin() ) + document_ += ","; + document_ += valueToQuotedString( name.c_str() ); + document_ += yamlCompatiblityEnabled_ ? ": " + : ":"; + writeValue( value[name] ); + } + document_ += "}"; + } + break; + } +} + + +// Class StyledWriter +// ////////////////////////////////////////////////////////////////// + +StyledWriter::StyledWriter() + : rightMargin_( 74 ) + , indentSize_( 3 ) +{ +} + + +std::string +StyledWriter::write( const Value &root ) +{ + document_ = ""; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + document_ += "\n"; + return document_; +} + + +void +StyledWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asLargestInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asLargestUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + for (;;) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + document_ += " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + for (;;) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + document_ += "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ", "; + document_ += childValues_[index]; + } + document_ += " ]"; + } + } +} + + +bool +StyledWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + document_ += value; +} + + +void +StyledWriter::writeIndent() +{ + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + document_ += '\n'; + } + document_ += indentString_; +} + + +void +StyledWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + document_ += value; +} + + +void +StyledWriter::indent() +{ + indentString_ += std::string( indentSize_, ' ' ); +} + + +void +StyledWriter::unindent() +{ + assert( int(indentString_.size()) >= indentSize_ ); + indentString_.resize( indentString_.size() - indentSize_ ); +} + + +void +StyledWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + document_ += normalizeEOL( root.getComment( commentBefore ) ); + document_ += "\n"; +} + + +void +StyledWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + document_ += " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + document_ += "\n"; + document_ += normalizeEOL( root.getComment( commentAfter ) ); + document_ += "\n"; + } +} + + +bool +StyledWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +// Class StyledStreamWriter +// ////////////////////////////////////////////////////////////////// + +StyledStreamWriter::StyledStreamWriter( std::string indentation ) + : document_(NULL) + , rightMargin_( 74 ) + , indentation_( indentation ) +{ +} + + +void +StyledStreamWriter::write( std::ostream &out, const Value &root ) +{ + document_ = &out; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + *document_ << "\n"; + document_ = NULL; // Forget the stream, for safety. +} + + +void +StyledStreamWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asLargestInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asLargestUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + for (;;) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + *document_ << " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledStreamWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + for (;;) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + *document_ << "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + *document_ << ", "; + *document_ << childValues_[index]; + } + *document_ << " ]"; + } + } +} + + +bool +StyledStreamWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledStreamWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + *document_ << value; +} + + +void +StyledStreamWriter::writeIndent() +{ + /* + Some comments in this method would have been nice. ;-) + + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + *document_ << '\n'; + } + */ + *document_ << '\n' << indentString_; +} + + +void +StyledStreamWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + *document_ << value; +} + + +void +StyledStreamWriter::indent() +{ + indentString_ += indentation_; +} + + +void +StyledStreamWriter::unindent() +{ + assert( indentString_.size() >= indentation_.size() ); + indentString_.resize( indentString_.size() - indentation_.size() ); +} + + +void +StyledStreamWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + *document_ << normalizeEOL( root.getComment( commentBefore ) ); + *document_ << "\n"; +} + + +void +StyledStreamWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + *document_ << " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + *document_ << "\n"; + *document_ << normalizeEOL( root.getComment( commentAfter ) ); + *document_ << "\n"; + } +} + + +bool +StyledStreamWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledStreamWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +std::ostream& operator<<( std::ostream &sout, const Value &root ) +{ + Json::StyledStreamWriter writer; + writer.write(sout, root); + return sout; +} + + +} // namespace Json + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: src/lib_json/json_writer.cpp +// ////////////////////////////////////////////////////////////////////// diff --git a/Core/Code/CppMicroServices/src/util/stdint_p.h b/Core/CppMicroServices/src/util/stdint_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/stdint_p.h rename to Core/CppMicroServices/src/util/stdint_p.h diff --git a/Core/Code/CppMicroServices/src/util/stdint_vc_p.h b/Core/CppMicroServices/src/util/stdint_vc_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/stdint_vc_p.h rename to Core/CppMicroServices/src/util/stdint_vc_p.h diff --git a/Core/Code/CppMicroServices/src/util/tinfl.c b/Core/CppMicroServices/src/util/tinfl.c similarity index 100% rename from Core/Code/CppMicroServices/src/util/tinfl.c rename to Core/CppMicroServices/src/util/tinfl.c diff --git a/Core/Code/CppMicroServices/src/util/usAny.cpp b/Core/CppMicroServices/src/util/usAny.cpp similarity index 73% rename from Core/Code/CppMicroServices/src/util/usAny.cpp rename to Core/CppMicroServices/src/util/usAny.cpp index fbfd8eb1ab..bac8be2580 100644 --- a/Core/Code/CppMicroServices/src/util/usAny.cpp +++ b/Core/CppMicroServices/src/util/usAny.cpp @@ -1,56 +1,78 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usAny.h" US_BEGIN_NAMESPACE +std::ostream& operator<< (std::ostream& os, const Any& any) +{ + return os << any.ToString(); +} + template std::string container_to_string(Iterator i1, Iterator i2) { std::stringstream ss; ss << "("; const Iterator begin = i1; for ( ; i1 != i2; ++i1) { if (i1 == begin) ss << *i1; else ss << "," << *i1; } ss << ")"; return ss.str(); } std::string any_value_to_string(const std::vector& val) { return container_to_string(val.begin(), val.end()); } std::string any_value_to_string(const std::list& val) { return container_to_string(val.begin(), val.end()); } std::string any_value_to_string(const std::vector& val) { return container_to_string(val.begin(), val.end()); } +std::string any_value_to_string(const std::map& val) +{ + std::stringstream ss; + ss << "["; + typedef std::map::const_iterator Iterator; + Iterator i1 = val.begin(); + const Iterator begin = i1; + const Iterator end = val.end(); + for ( ; i1 != end; ++i1) + { + if (i1 == begin) ss << "\"" << i1->first << "\" => " << i1->second; + else ss << ", " << "\"" << i1->first << "\" => " << i1->second; + } + ss << "]"; + return ss.str(); +} + US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usAny.h b/Core/CppMicroServices/src/util/usAny.h similarity index 98% rename from Core/Code/CppMicroServices/src/util/usAny.h rename to Core/CppMicroServices/src/util/usAny.h index 8c0e4df75d..01b69af5d8 100644 --- a/Core/Code/CppMicroServices/src/util/usAny.h +++ b/Core/CppMicroServices/src/util/usAny.h @@ -1,400 +1,397 @@ /*============================================================================= Library: CppMicroServices Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. Extracted from Boost 1.46.1 and adapted for CppMicroServices. Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =========================================================================*/ #ifndef US_ANY_H #define US_ANY_H #include #include #include #include #include +#include #include US_BEGIN_NAMESPACE template std::string any_value_to_string(const T& val); US_EXPORT std::string any_value_to_string(const std::vector& val); US_EXPORT std::string any_value_to_string(const std::list& val); /** * \ingroup MicroServicesUtils * * An Any class represents a general type and is capable of storing any type, supporting type-safe extraction * of the internally stored data. * * Code taken from the Boost 1.46.1 library. Original copyright by Kevlin Henney. Modified for CppMicroServices. */ class Any { public: /** * Creates an empty any type. */ Any(): _content(0) { } /** * Creates an Any which stores the init parameter inside. * * \param value The content of the Any * * Example: * \code * Any a(13); * Any a(string("12345")); * \endcode */ template Any(const ValueType& value) : _content(new Holder(value)) { } /** * Copy constructor, works with empty Anys and initialized Any values. * * \param other The Any to copy */ Any(const Any& other) : _content(other._content ? other._content->Clone() : 0) { } ~Any() { delete _content; } /** * Swaps the content of the two Anys. * * \param rhs The Any to swap this Any with. */ Any& Swap(Any& rhs) { std::swap(_content, rhs._content); return *this; } /** * Assignment operator for all types != Any. * * \param rhs The value which should be assigned to this Any. * * Example: * \code * Any a = 13; * Any a = string("12345"); * \endcode */ template Any& operator = (const ValueType& rhs) { Any(rhs).Swap(*this); return *this; } /** * Assignment operator for Any. * * \param rhs The Any which should be assigned to this Any. */ Any& operator = (const Any& rhs) { Any(rhs).Swap(*this); return *this; } /** * returns true if the Any is empty */ bool Empty() const { return !_content; } /** * Returns a string representation for the content. * * Custom types should either provide a std::ostream& operator<<(std::ostream& os, const CustomType& ct) * function or specialize the any_value_to_string template function for meaningful output. */ std::string ToString() const { return _content->ToString(); } /** * Returns the type information of the stored content. * If the Any is empty typeid(void) is returned. * It is suggested to always query an Any for its type info before trying to extract * data via an any_cast/ref_any_cast. */ const std::type_info& Type() const { return _content ? _content->Type() : typeid(void); } private: class Placeholder { public: virtual ~Placeholder() { } virtual std::string ToString() const = 0; virtual const std::type_info& Type() const = 0; virtual Placeholder* Clone() const = 0; }; template class Holder: public Placeholder { public: Holder(const ValueType& value) : _held(value) { } virtual std::string ToString() const { return any_value_to_string(_held); } virtual const std::type_info& Type() const { return typeid(ValueType); } virtual Placeholder* Clone() const { return new Holder(_held); } ValueType _held; private: // intentionally left unimplemented Holder& operator=(const Holder &); }; private: template friend ValueType* any_cast(Any*); template friend ValueType* unsafe_any_cast(Any*); Placeholder* _content; }; class BadAnyCastException : public std::bad_cast { public: BadAnyCastException(const std::string& msg = "") : std::bad_cast(), _msg(msg) {} ~BadAnyCastException() throw() {} virtual const char * what() const throw() { if (_msg.empty()) return "US_PREPEND_NAMESPACE(BadAnyCastException): " "failed conversion using US_PREPEND_NAMESPACE(any_cast)"; else return _msg.c_str(); } private: std::string _msg; }; /** * any_cast operator used to extract the ValueType from an Any*. Will return a pointer * to the stored value. * * Example Usage: * \code * MyType* pTmp = any_cast(pAny) * \endcode * Will return NULL if the cast fails, i.e. types don't match. */ template ValueType* any_cast(Any* operand) { return operand && operand->Type() == typeid(ValueType) ? &static_cast*>(operand->_content)->_held : 0; } /** * any_cast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer * to the stored value. * * Example Usage: * \code * const MyType* pTmp = any_cast(pAny) * \endcode * Will return NULL if the cast fails, i.e. types don't match. */ template const ValueType* any_cast(const Any* operand) { return any_cast(const_cast(operand)); } /** * any_cast operator used to extract a copy of the ValueType from an const Any&. * * Example Usage: * \code * MyType tmp = any_cast(anAny) * \endcode * Will throw a BadCastException if the cast fails. * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in * these cases. */ template ValueType any_cast(const Any& operand) { ValueType* result = any_cast(const_cast(&operand)); if (!result) throw BadAnyCastException("Failed to convert between const Any types"); return *result; } /** * any_cast operator used to extract a copy of the ValueType from an Any&. * * Example Usage: * \code * MyType tmp = any_cast(anAny) * \endcode * Will throw a BadCastException if the cast fails. * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in * these cases. */ template ValueType any_cast(Any& operand) { ValueType* result = any_cast(&operand); if (!result) throw BadAnyCastException("Failed to convert between Any types"); return *result; } /** * ref_any_cast operator used to return a const reference to the internal data. * * Example Usage: * \code * const MyType& tmp = ref_any_cast(anAny); * \endcode */ template const ValueType& ref_any_cast(const Any & operand) { ValueType* result = any_cast(const_cast(&operand)); if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between const Any types"); return *result; } /** * ref_any_cast operator used to return a reference to the internal data. * * Example Usage: * \code * MyType& tmp = ref_any_cast(anAny); * \endcode */ template ValueType& ref_any_cast(Any& operand) { ValueType* result = any_cast(&operand); if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between Any types"); return *result; } /** * \internal * * The "unsafe" versions of any_cast are not part of the * public interface and may be removed at any time. They are * required where we know what type is stored in the any and can't * use typeid() comparison, e.g., when our types may travel across * different shared libraries. */ template ValueType* unsafe_any_cast(Any* operand) { return &static_cast*>(operand->_content)->_held; } /** * \internal * * The "unsafe" versions of any_cast are not part of the * public interface and may be removed at any time. They are * required where we know what type is stored in the any and can't * use typeid() comparison, e.g., when our types may travel across * different shared libraries. */ template const ValueType* unsafe_any_cast(const Any* operand) { return any_cast(const_cast(operand)); } US_EXPORT std::string any_value_to_string(const std::vector& val); +US_EXPORT std::string any_value_to_string(const std::map& val); template std::string any_value_to_string(const T& val) { std::stringstream ss; ss << val; return ss.str(); } US_END_NAMESPACE -inline std::ostream& operator<< (std::ostream& os, const US_PREPEND_NAMESPACE(Any)& any) -{ - return os << any.ToString(); -} - #endif // US_ANY_H diff --git a/Core/Code/CppMicroServices/src/util/usAtomicInt_p.h b/Core/CppMicroServices/src/util/usAtomicInt_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usAtomicInt_p.h rename to Core/CppMicroServices/src/util/usAtomicInt_p.h diff --git a/Core/Code/CppMicroServices/src/util/usFunctor_p.h b/Core/CppMicroServices/src/util/usFunctor_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usFunctor_p.h rename to Core/CppMicroServices/src/util/usFunctor_p.h diff --git a/Core/Code/CppMicroServices/src/util/usSharedData.h b/Core/CppMicroServices/src/util/usSharedData.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usSharedData.h rename to Core/CppMicroServices/src/util/usSharedData.h diff --git a/Core/CppMicroServices/src/util/usSharedLibrary.cpp b/Core/CppMicroServices/src/util/usSharedLibrary.cpp new file mode 100644 index 0000000000..5bead2eaed --- /dev/null +++ b/Core/CppMicroServices/src/util/usSharedLibrary.cpp @@ -0,0 +1,273 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usSharedLibrary.h" + +#include + +#include +#include +#include + + +#if defined(US_PLATFORM_POSIX) + #include +#elif defined(US_PLATFORM_WINDOWS) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include +#else + #error Unsupported platform +#endif + + +US_BEGIN_NAMESPACE + +#ifdef US_PLATFORM_POSIX +static const char PATH_SEPARATOR = '/'; +#else +static const char PATH_SEPARATOR = '\\'; +#endif + +class SharedLibraryPrivate : public SharedData +{ +public: + + SharedLibraryPrivate() + : m_Handle(NULL) + #ifdef US_PLATFORM_WINDOWS + , m_Suffix(".dll") + #elif defined(US_PLATFORM_APPLE) + , m_Suffix(".dylib") + , m_Prefix("lib") + #else + , m_Suffix(".so") + , m_Prefix("lib") + #endif + {} + + void* m_Handle; + + std::string m_Name; + std::string m_Path; + std::string m_FilePath; + std::string m_Suffix; + std::string m_Prefix; + +}; + +SharedLibrary::SharedLibrary() + : d(new SharedLibraryPrivate) +{ +} + +SharedLibrary::SharedLibrary(const SharedLibrary& other) + : d(other.d) +{ +} + +SharedLibrary::SharedLibrary(const std::string& libPath, const std::string& name) + : d(new SharedLibraryPrivate) +{ + d->m_Name = name; + d->m_Path = libPath; +} + +SharedLibrary::SharedLibrary(const std::string& absoluteFilePath) + : d(new SharedLibraryPrivate) +{ + d->m_FilePath = absoluteFilePath; + SetFilePath(absoluteFilePath); +} + +SharedLibrary::~SharedLibrary() +{ +} + +SharedLibrary& SharedLibrary::operator =(const SharedLibrary& other) +{ + d = other.d; + return *this; +} + +void SharedLibrary::Load(int flags) +{ + if (d->m_Handle) throw std::logic_error(std::string("Library already loaded: ") + GetFilePath()); + std::string libPath = GetFilePath(); +#ifdef US_PLATFORM_POSIX + d->m_Handle = dlopen(libPath.c_str(), flags); + if (!d->m_Handle) + { + const char* err = dlerror(); + throw std::runtime_error(err ? std::string(err) : (std::string("Error loading ") + libPath)); + } +#else + d->m_Handle = LoadLibrary(libPath.c_str()); + if (!d->m_Handle) + { + std::string errMsg = "Loading "; + errMsg.append(libPath).append("failed with error: ").append(GetLastErrorStr()); + + throw std::runtime_error(errMsg); + } +#endif +} + +void SharedLibrary::Load() +{ +#ifdef US_PLATFORM_POSIX +#ifdef US_GCC_RTTI_WORKAROUND_NEEDED + Load(RTLD_LAZY | RTLD_GLOBAL); +#else + Load(RTLD_LAZY | RTLD_LOCAL); +#endif +#else + Load(0); +#endif +} + +void SharedLibrary::Unload() +{ + if (d->m_Handle) + { +#ifdef US_PLATFORM_POSIX + if (dlclose(d->m_Handle)) + { + const char* err = dlerror(); + throw std::runtime_error(err ? std::string(err) : (std::string("Error unloading ") + GetLibraryPath())); + } +#else + if (!FreeLibrary((HMODULE)d->m_Handle)) + { + std::string errMsg = "Unloading "; + errMsg.append(GetLibraryPath()).append("failed with error: ").append(GetLastErrorStr()); + + throw std::runtime_error(errMsg); + } +#endif + d->m_Handle = 0; + } +} + +void SharedLibrary::SetName(const std::string& name) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Name = name; +} + +std::string SharedLibrary::GetName() const +{ + return d->m_Name; +} + +std::string SharedLibrary::GetFilePath(const std::string& name) const +{ + if (!d->m_FilePath.empty()) return d->m_FilePath; + return GetLibraryPath() + PATH_SEPARATOR + GetPrefix() + name + GetSuffix(); +} + +void SharedLibrary::SetFilePath(const std::string& absoluteFilePath) +{ + if (IsLoaded()) return; + + d.Detach(); + d->m_FilePath = absoluteFilePath; + + std::string name = d->m_FilePath; + std::size_t pos = d->m_FilePath.find_last_of(PATH_SEPARATOR); + if (pos != std::string::npos) + { + d->m_Path = d->m_FilePath.substr(0, pos); + name = d->m_FilePath.substr(pos+1); + } + else + { + d->m_Path.clear(); + } + + if (name.size() >= d->m_Prefix.size() && + name.compare(0, d->m_Prefix.size(), d->m_Prefix) == 0) + { + name = name.substr(d->m_Prefix.size()); + } + if (name.size() >= d->m_Suffix.size() && + name.compare(name.size()-d->m_Suffix.size(), d->m_Suffix.size(), d->m_Suffix) == 0) + { + name = name.substr(0, name.size()-d->m_Suffix.size()); + } + d->m_Name = name; +} + +std::string SharedLibrary::GetFilePath() const +{ + return GetFilePath(d->m_Name); +} + +void SharedLibrary::SetLibraryPath(const std::string& path) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Path = path; +} + +std::string SharedLibrary::GetLibraryPath() const +{ + return d->m_Path; +} + +void SharedLibrary::SetSuffix(const std::string& suffix) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Suffix = suffix; +} + +std::string SharedLibrary::GetSuffix() const +{ + return d->m_Suffix; +} + +void SharedLibrary::SetPrefix(const std::string& prefix) +{ + if (IsLoaded() || !d->m_FilePath.empty()) return; + d.Detach(); + d->m_Prefix = prefix; +} + +std::string SharedLibrary::GetPrefix() const +{ + return d->m_Prefix; +} + +void* SharedLibrary::GetHandle() const +{ + return d->m_Handle; +} + +bool SharedLibrary::IsLoaded() const +{ + return d->m_Handle != NULL; +} + +US_END_NAMESPACE diff --git a/Core/CppMicroServices/src/util/usSharedLibrary.h b/Core/CppMicroServices/src/util/usSharedLibrary.h new file mode 100644 index 0000000000..5bcd9308db --- /dev/null +++ b/Core/CppMicroServices/src/util/usSharedLibrary.h @@ -0,0 +1,223 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#ifndef USSHAREDLIBRARY_H +#define USSHAREDLIBRARY_H + +#include "usConfig.h" +#include "usSharedData.h" + +#include + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4251) +#endif + +US_BEGIN_NAMESPACE + +class SharedLibraryPrivate; + +/** + * \ingroup MicroServicesUtils + * + * The SharedLibrary class loads shared libraries at runtime. + */ +class US_EXPORT SharedLibrary +{ +public: + + SharedLibrary(); + SharedLibrary(const SharedLibrary& other); + + /** + * Construct a SharedLibrary object using a library search path and + * a library base name. + * + * @param libPath An absolute path containing the shared library + * @param name The base name of the shared library, without prefix + * and suffix. + */ + SharedLibrary(const std::string& libPath, const std::string& name); + + /** + * Construct a SharedLibrary object using an absolute file path to + * the shared library. Using this constructor effectively disables + * all setters except SetFilePath(). + * + * @param absoluteFilePath The absolute path to the shared library. + */ + SharedLibrary(const std::string& absoluteFilePath); + + /** + * Destroys this object but does not unload the shared library. + */ + ~SharedLibrary(); + + SharedLibrary& operator=(const SharedLibrary& other); + + /** + * Loads the shared library pointed to by this SharedLibrary object. + * On POSIX systems dlopen() is called with the RTLD_LAZY and + * RTLD_LOCAL flags unless the compiler is gcc 4.4.x or older. Then + * the RTLD_LAZY and RTLD_GLOBAL flags are used to load the shared library + * to work around RTTI problems across shared library boundaries. + * + * @throws std::logic_error If the library is already loaded. + * @throws std::runtime_error If loading the library failed. + */ + void Load(); + + /** + * Loads the shared library pointed to by this SharedLibrary object, + * using the specified flags on POSIX systems. + * + * @throws std::logic_error If the library is already loaded. + * @throws std::runtime_error If loading the library failed. + */ + void Load(int flags); + + /** + * Un-loads the shared library pointed to by this SharedLibrary object. + * + * @throws std::runtime_error If an error occurred while un-loading the + * shared library. + */ + void Unload(); + + /** + * Sets the base name of the shared library. Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param name The base name of the shared library, without prefix and + * suffix. + */ + void SetName(const std::string& name); + + /** + * Gets the base name of the shared library. + * @return The shared libraries base name. + */ + std::string GetName() const; + + /** + * Gets the absolute file path for the shared library with base name + * \c name, using the search path returned by GetLibraryPath(). + * + * @param name The shared library base name. + * @return The absolute file path of the shared library. + */ + std::string GetFilePath(const std::string& name) const; + + /** + * Sets the absolute file path of this SharedLibrary object. + * Using this methods with a non-empty \c absoluteFilePath argument + * effectively disables all other setters. + * + * @param absoluteFilePath The new absolute file path of this SharedLibrary + * object. + */ + void SetFilePath(const std::string& absoluteFilePath); + + /** + * Gets the absolute file path of this SharedLibrary object. + * + * @return The absolute file path of the shared library. + */ + std::string GetFilePath() const; + + /** + * Sets a new library search path. Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param path The new shared library search path. + */ + void SetLibraryPath(const std::string& path); + + /** + * Gets the library search path of this SharedLibrary object. + * + * @return The library search path. + */ + std::string GetLibraryPath() const; + + /** + * Sets the suffix for shared library names (e.g. lib). Does nothing if the shared + * library is already loaded or the SharedLibrary(const std::string&) + * constructor was used. + * + * @param suffix The shared library name suffix. + */ + void SetSuffix(const std::string& suffix); + + /** + * Gets the file name suffix of this SharedLibrary object. + * + * @return The file name suffix of the shared library. + */ + std::string GetSuffix() const; + + /** + * Sets the file name prefix for shared library names (e.g. .dll or .so). + * Does nothing if the shared library is already loaded or the + * SharedLibrary(const std::string&) constructor was used. + * + * @param prefix The shared library name prefix. + */ + void SetPrefix(const std::string& prefix); + + /** + * Gets the file name prefix of this SharedLibrary object. + * + * @return The file name prefix of the shared library. + */ + std::string GetPrefix() const; + + /** + * Gets the internal handle of this SharedLibrary object. + * + * @return \c NULL if the shared library is not loaded, the operating + * system specific handle otherwise. + */ + void* GetHandle() const; + + /** + * Gets the loaded/unloaded stated of this SharedLibrary object. + * + * @return \c true if the shared library is loaded, \c false otherwise. + */ + bool IsLoaded() const; + +private: + + ExplicitlySharedDataPointer d; + +}; + +US_END_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // USTESTUTILSHAREDLIBRARY_H diff --git a/Core/Code/CppMicroServices/src/util/usStaticInit_p.h b/Core/CppMicroServices/src/util/usStaticInit_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usStaticInit_p.h rename to Core/CppMicroServices/src/util/usStaticInit_p.h diff --git a/Core/Code/CppMicroServices/src/util/usThreads.cpp b/Core/CppMicroServices/src/util/usThreads.cpp similarity index 99% rename from Core/Code/CppMicroServices/src/util/usThreads.cpp rename to Core/CppMicroServices/src/util/usThreads.cpp index f26bc0c023..4464c9038e 100644 --- a/Core/Code/CppMicroServices/src/util/usThreads.cpp +++ b/Core/CppMicroServices/src/util/usThreads.cpp @@ -1,255 +1,254 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usThreads_p.h" #include "usUtils_p.h" #ifdef US_PLATFORM_POSIX #include #include #endif US_BEGIN_NAMESPACE WaitCondition::WaitCondition() { #ifdef US_ENABLE_THREADING_SUPPORT #ifdef US_PLATFORM_POSIX pthread_cond_init(&m_WaitCondition, 0); #else m_NumberOfWaiters = 0; m_WasNotifyAll = 0; m_Semaphore = CreateSemaphore(0, // no security 0, // initial value 0x7fffffff, // max count 0); // unnamed InitializeCriticalSection(&m_NumberOfWaitersLock); m_WaitersAreDone = CreateEvent(0, // no security FALSE, // auto-reset FALSE, // non-signaled initially 0 ); // unnamed #endif #endif } WaitCondition::~WaitCondition() { #ifdef US_ENABLE_THREADING_SUPPORT #ifdef US_PLATFORM_POSIX pthread_cond_destroy(&m_WaitCondition); #else CloseHandle(m_Semaphore); CloseHandle(m_WaitersAreDone); DeleteCriticalSection(&m_NumberOfWaitersLock); #endif #endif } void WaitCondition::Notify() { #ifdef US_ENABLE_THREADING_SUPPORT #ifdef US_PLATFORM_POSIX pthread_cond_signal(&m_WaitCondition); #else EnterCriticalSection(&m_NumberOfWaitersLock); int haveWaiters = m_NumberOfWaiters > 0; LeaveCriticalSection(&m_NumberOfWaitersLock); // if there were not any waiters, then this is a no-op if (haveWaiters) { ReleaseSemaphore(m_Semaphore, 1, 0); } #endif #endif } void WaitCondition::NotifyAll() { #ifdef US_ENABLE_THREADING_SUPPORT #ifdef US_PLATFORM_POSIX pthread_cond_broadcast(&m_WaitCondition); #else // This is needed to ensure that m_NumberOfWaiters and m_WasNotifyAll are // consistent EnterCriticalSection(&m_NumberOfWaitersLock); int haveWaiters = 0; if (m_NumberOfWaiters > 0) { // We are broadcasting, even if there is just one waiter... // Record that we are broadcasting, which helps optimize Notify() // for the non-broadcast case m_WasNotifyAll = 1; haveWaiters = 1; } if (haveWaiters) { // Wake up all waiters atomically ReleaseSemaphore(m_Semaphore, m_NumberOfWaiters, 0); LeaveCriticalSection(&m_NumberOfWaitersLock); // Wait for all the awakened threads to acquire the counting // semaphore WaitForSingleObject(m_WaitersAreDone, INFINITE); // This assignment is ok, even without the m_NumberOfWaitersLock held // because no other waiter threads can wake up to access it. m_WasNotifyAll = 0; } else { LeaveCriticalSection(&m_NumberOfWaitersLock); } #endif #endif } bool WaitCondition::Wait(MutexType* mutex, unsigned long timeoutMillis) { return Wait(*mutex, timeoutMillis); } #ifdef US_ENABLE_THREADING_SUPPORT bool WaitCondition::Wait(MutexType& mutex, unsigned long timeoutMillis) { #ifdef US_PLATFORM_POSIX struct timespec ts, * pts = 0; if (timeoutMillis) { pts = &ts; struct timeval tv; int error = gettimeofday(&tv, NULL); if (error) { US_ERROR << "gettimeofday error: " << GetLastErrorStr(); return false; } ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; ts.tv_sec += timeoutMillis / 1000; ts.tv_nsec += (timeoutMillis % 1000) * 1000000; ts.tv_sec += ts.tv_nsec / 1000000000; ts.tv_nsec = ts.tv_nsec % 1000000000; } if (pts) { int error = pthread_cond_timedwait(&m_WaitCondition, &mutex.m_Mtx, pts); if (error == 0) { return true; } else { if (error != ETIMEDOUT) { US_ERROR << "pthread_cond_timedwait error: " << GetLastErrorStr(); } return false; } } else { int error = pthread_cond_wait(&m_WaitCondition, &mutex.m_Mtx); if (error) { US_ERROR << "pthread_cond_wait error: " << GetLastErrorStr(); return false; } return true; } #else // Avoid race conditions EnterCriticalSection(&m_NumberOfWaitersLock); m_NumberOfWaiters++; LeaveCriticalSection(&m_NumberOfWaitersLock); DWORD dw; bool result = true; // This call atomically releases the mutex and waits on the // semaphore until signaled dw = SignalObjectAndWait(mutex.m_Mtx, m_Semaphore, timeoutMillis ? timeoutMillis : INFINITE, FALSE); if (dw == WAIT_TIMEOUT) { result = false; } else if (dw == WAIT_FAILED) { result = false; US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); } // Reacquire lock to avoid race conditions EnterCriticalSection(&m_NumberOfWaitersLock); // We're no longer waiting.... m_NumberOfWaiters--; // Check to see if we're the last waiter after the broadcast int lastWaiter = m_WasNotifyAll && m_NumberOfWaiters == 0; LeaveCriticalSection(&m_NumberOfWaitersLock); // If we're the last waiter thread during this particular broadcast // then let the other threads proceed if (lastWaiter) { // This call atomically signals the m_WaitersAreDone event and waits // until it can acquire the external mutex. This is required to // ensure fairness dw = SignalObjectAndWait(m_WaitersAreDone, mutex.m_Mtx, INFINITE, FALSE); if (result && dw == WAIT_FAILED) { result = false; US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); } } else { // Always regain the external mutex since that's the guarentee we // give to our callers dw = WaitForSingleObject(mutex.m_Mtx, INFINITE); if (result && dw == WAIT_FAILED) { result = false; US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); } } return result; #endif } #else bool WaitCondition::Wait(MutexType&, unsigned long) { return true; } #endif US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/util/usThreads_p.h b/Core/CppMicroServices/src/util/usThreads_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usThreads_p.h rename to Core/CppMicroServices/src/util/usThreads_p.h diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.c b/Core/CppMicroServices/src/util/usUncompressResourceData.c similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUncompressResourceData.c rename to Core/CppMicroServices/src/util/usUncompressResourceData.c diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.cpp b/Core/CppMicroServices/src/util/usUncompressResourceData.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUncompressResourceData.cpp rename to Core/CppMicroServices/src/util/usUncompressResourceData.cpp diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h b/Core/CppMicroServices/src/util/usUncompressResourceData.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUncompressResourceData.h rename to Core/CppMicroServices/src/util/usUncompressResourceData.h diff --git a/Core/Code/CppMicroServices/src/util/usUtils.cpp b/Core/CppMicroServices/src/util/usUtils.cpp similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUtils.cpp rename to Core/CppMicroServices/src/util/usUtils.cpp diff --git a/Core/Code/CppMicroServices/src/util/usUtils_p.h b/Core/CppMicroServices/src/util/usUtils_p.h similarity index 100% rename from Core/Code/CppMicroServices/src/util/usUtils_p.h rename to Core/CppMicroServices/src/util/usUtils_p.h diff --git a/Core/Code/CppMicroServices/test/CMakeLists.txt b/Core/CppMicroServices/test/CMakeLists.txt similarity index 71% rename from Core/Code/CppMicroServices/test/CMakeLists.txt rename to Core/CppMicroServices/test/CMakeLists.txt index c762ed9048..c4bb27b578 100644 --- a/Core/Code/CppMicroServices/test/CMakeLists.txt +++ b/Core/CppMicroServices/test/CMakeLists.txt @@ -1,102 +1,87 @@ #----------------------------------------------------------------------------- # Configure files, include dirs, etc. #----------------------------------------------------------------------------- configure_file("${CMAKE_CURRENT_SOURCE_DIR}/usTestingConfig.h.in" "${PROJECT_BINARY_DIR}/include/usTestingConfig.h") include_directories(${US_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}) -if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - include_directories(${US_BASECLASS_INCLUDE_DIRS}) -endif() - -link_directories(${US_LINK_DIRS}) -if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - link_directories(${US_BASECLASS_LIBRARY_DIRS}) -endif() #----------------------------------------------------------------------------- # Create test modules #----------------------------------------------------------------------------- include(usFunctionCreateTestModule) set(_us_test_module_libs "" CACHE INTERNAL "" FORCE) add_subdirectory(modules) #----------------------------------------------------------------------------- # Add unit tests #----------------------------------------------------------------------------- set(_tests usDebugOutputTest usLDAPFilterTest usModuleTest usModuleResourceTest + usServiceFactoryTest + usServiceRegistryPerformanceTest usServiceRegistryTest + usServiceTemplateTest usServiceTrackerTest usStaticModuleResourceTest usStaticModuleTest ) if(US_BUILD_SHARED_LIBS) - list(APPEND _tests usServiceListenerTest) + list(APPEND _tests usServiceListenerTest usModuleManifestTest usSharedLibraryTest) if(US_ENABLE_AUTOLOADING_SUPPORT) list(APPEND _tests usModuleAutoLoadTest) endif() endif() set(_additional_srcs usTestManager.cpp usTestUtilModuleListener.cpp - usTestUtilSharedLibrary.cpp ) set(_test_driver ${PROJECT_NAME}TestDriver) set(_test_sourcelist_extra_args ) create_test_sourcelist(_srcs ${_test_driver}.cpp ${_tests} ${_test_sourcelist_extra_args}) -usFunctionEmbedResources(_srcs EXECUTABLE_NAME ${_test_driver} FILES usTestResource.txt) +usFunctionEmbedResources(_srcs EXECUTABLE_NAME ${_test_driver} FILES usTestResource.txt manifest.json) # Generate a custom "module init" file for the test driver executable -set(MODULE_DEPENDS_STR ) -foreach(_dep ${US_LINK_LIBRARIES}) - set(MODULE_DEPENDS_STR "${MODULE_DEPENDS_STR} ${_dep}") -endforeach() - if(US_BUILD_SHARED_LIBS) - usFunctionGenerateModuleInit(_srcs - NAME ${_test_driver} - DEPENDS "${MODULE_DEPENDS_STR}" - VERSION "0.1.0" - EXECUTABLE - ) + usFunctionGenerateExecutableInit(_srcs IDENTIFIER ${_test_driver}) endif() add_executable(${_test_driver} ${_srcs} ${_additional_srcs}) if(NOT US_BUILD_SHARED_LIBS) target_link_libraries(${_test_driver} ${_us_test_module_libs}) endif() -target_link_libraries(${_test_driver} ${US_LINK_LIBRARIES}) +target_link_libraries(${_test_driver} ${US_LIBRARY_TARGET}) -if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - target_link_libraries(${_test_driver} ${US_BASECLASS_LIBRARIES}) +if(UNIX AND NOT APPLE) + target_link_libraries(${_test_driver} rt) endif() # Register tests foreach(_test ${_tests}) add_test(NAME ${_test} COMMAND ${_test_driver} ${_test}) endforeach() + if(US_TEST_LABELS) set_tests_properties(${_tests} PROPERTIES LABELS "${US_TEST_LABELS}") endif() #----------------------------------------------------------------------------- # Add dependencies for shared libraries #----------------------------------------------------------------------------- if(US_BUILD_SHARED_LIBS) foreach(_test_module ${_us_test_module_libs}) add_dependencies(${_test_driver} ${_test_module}) endforeach() endif() diff --git a/Core/CppMicroServices/test/manifest.json b/Core/CppMicroServices/test/manifest.json new file mode 100644 index 0000000000..fb898a5477 --- /dev/null +++ b/Core/CppMicroServices/test/manifest.json @@ -0,0 +1,3 @@ +{ + "module.version" : "0.1.0" +} diff --git a/Core/Code/CppMicroServices/test/modules/CMakeLists.txt b/Core/CppMicroServices/test/modules/CMakeLists.txt similarity index 85% rename from Core/Code/CppMicroServices/test/modules/CMakeLists.txt rename to Core/CppMicroServices/test/modules/CMakeLists.txt index 6d02314c68..f303ee9753 100644 --- a/Core/Code/CppMicroServices/test/modules/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/CMakeLists.txt @@ -1,11 +1,13 @@ add_subdirectory(libA) add_subdirectory(libA2) add_subdirectory(libAL) add_subdirectory(libAL2) add_subdirectory(libBWithStatic) +add_subdirectory(libH) +add_subdirectory(libM) add_subdirectory(libS) add_subdirectory(libSL1) add_subdirectory(libSL3) add_subdirectory(libSL4) add_subdirectory(libRWithResources) diff --git a/Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt b/Core/CppMicroServices/test/modules/libA/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libA/CMakeLists.txt index c3b4969f7b..48211b0c66 100644 --- a/Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libA/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleA usTestModuleA.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp b/Core/CppMicroServices/test/modules/libA/usTestModuleA.cpp similarity index 92% rename from Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp rename to Core/CppMicroServices/test/modules/libA/usTestModuleA.cpp index e2333c2bee..a654901ef2 100644 --- a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp +++ b/Core/CppMicroServices/test/modules/libA/usTestModuleA.cpp @@ -1,80 +1,77 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usTestModuleAService.h" #include #include #include -#include US_BASECLASS_HEADER - US_BEGIN_NAMESPACE -struct TestModuleA : public US_BASECLASS_NAME, public TestModuleAService +struct TestModuleA : public TestModuleAService { TestModuleA(ModuleContext* mc) { US_INFO << "Registering TestModuleAService"; sr = mc->RegisterService(this); } void Unregister() { if (sr) { sr.Unregister(); sr = 0; } } private: - ServiceRegistration sr; + ServiceRegistration sr; }; class TestModuleAActivator : public ModuleActivator { public: TestModuleAActivator() : s(0) {} ~TestModuleAActivator() { delete s; } void Load(ModuleContext* context) { s = new TestModuleA(context); } void Unload(ModuleContext*) { } private: TestModuleA* s; }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleA, US_PREPEND_NAMESPACE(TestModuleAActivator)) - diff --git a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleAService.h b/Core/CppMicroServices/test/modules/libA/usTestModuleAService.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libA/usTestModuleAService.h rename to Core/CppMicroServices/test/modules/libA/usTestModuleAService.h diff --git a/Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt b/Core/CppMicroServices/test/modules/libA2/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libA2/CMakeLists.txt index 28340c7d2c..21968cba8c 100644 --- a/Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libA2/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleA2 usTestModuleA2.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp b/Core/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp similarity index 92% rename from Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp rename to Core/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp index 187870044f..d2d03adeeb 100644 --- a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp +++ b/Core/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp @@ -1,79 +1,76 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usTestModuleA2Service.h" #include #include -#include US_BASECLASS_HEADER - US_BEGIN_NAMESPACE -struct TestModuleA2 : public US_BASECLASS_NAME, public TestModuleA2Service +struct TestModuleA2 : public TestModuleA2Service { TestModuleA2(ModuleContext* mc) { US_INFO << "Registering TestModuleA2Service"; sr = mc->RegisterService(this); } void Unregister() { if (sr) { sr.Unregister(); } } private: - ServiceRegistration sr; + ServiceRegistration sr; }; class TestModuleA2Activator : public ModuleActivator { public: TestModuleA2Activator() : s(0) {} ~TestModuleA2Activator() { delete s; } void Load(ModuleContext* context) { s = new TestModuleA2(context); } void Unload(ModuleContext* /*context*/) { s->Unregister(); } private: TestModuleA2* s; }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleA2, US_PREPEND_NAMESPACE(TestModuleA2Activator)) - diff --git a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h b/Core/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h rename to Core/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h diff --git a/Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libAL/CMakeLists.txt index 83a38c679b..224c6f09cb 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libAL/CMakeLists.txt @@ -1,5 +1,4 @@ usFunctionCreateTestModule(TestModuleAL usTestModuleAL.cpp) add_subdirectory(libAL_1) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt index 11c58a935f..5db0e45894 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt @@ -1,7 +1,6 @@ foreach(_type ARCHIVE LIBRARY RUNTIME) set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CMAKE_${_type}_OUTPUT_DIRECTORY}/TestModuleAL) endforeach() usFunctionCreateTestModule(TestModuleAL_1 usTestModuleAL_1.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp b/Core/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp rename to Core/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp index 1c0ca73f54..dd15f10b16 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp +++ b/Core/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp @@ -1,31 +1,30 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include US_BEGIN_NAMESPACE struct US_ABI_EXPORT TestModuleAL_1_Dummy { }; US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp rename to Core/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp index 9b0abf1b25..aaee431545 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ b/Core/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp @@ -1,31 +1,30 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include US_BEGIN_NAMESPACE struct TestModuleAL_Dummy { }; US_END_NAMESPACE - diff --git a/Core/CppMicroServices/test/modules/libAL2/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL2/CMakeLists.txt new file mode 100644 index 0000000000..8fefb1736d --- /dev/null +++ b/Core/CppMicroServices/test/modules/libAL2/CMakeLists.txt @@ -0,0 +1,4 @@ + +usFunctionCreateTestModuleWithResources(TestModuleAL2 SOURCES usTestModuleAL2.cpp RESOURCES manifest.json) + +add_subdirectory(libAL2_1) diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt b/Core/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt index 074d20f014..7c65e41ee5 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt @@ -1,7 +1,6 @@ foreach(_type ARCHIVE LIBRARY RUNTIME) set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CMAKE_${_type}_OUTPUT_DIRECTORY}/autoload_al2) endforeach() usFunctionCreateTestModule(TestModuleAL2_1 usTestModuleAL2_1.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp b/Core/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp rename to Core/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp index 684e38c5d3..b81eb15a35 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp +++ b/Core/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp @@ -1,31 +1,30 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include US_BEGIN_NAMESPACE struct US_ABI_EXPORT TestModuleAL2_1_Dummy { }; US_END_NAMESPACE - diff --git a/Core/CppMicroServices/test/modules/libAL2/resources/manifest.json b/Core/CppMicroServices/test/modules/libAL2/resources/manifest.json new file mode 100644 index 0000000000..4772f1f57c --- /dev/null +++ b/Core/CppMicroServices/test/modules/libAL2/resources/manifest.json @@ -0,0 +1,3 @@ +{ + "module.autoload_dir" : "autoload_al2" +} diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp b/Core/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp rename to Core/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp index 6f81242b11..0388565838 100644 --- a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp +++ b/Core/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp @@ -1,31 +1,30 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include US_BEGIN_NAMESPACE struct TestModuleAL2_Dummy { }; US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt b/Core/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/res.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources/res.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/res.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources/res.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt b/Core/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt rename to Core/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp similarity index 94% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp rename to Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp index 1b18b2a4c8..7111c3164a 100644 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp +++ b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp @@ -1,73 +1,71 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usTestModuleBService.h" #include #include #include #include -#include US_BASECLASS_HEADER - US_BEGIN_NAMESPACE -struct TestModuleB : public US_BASECLASS_NAME, public TestModuleBService +struct TestModuleB : public TestModuleBService { TestModuleB(ModuleContext* mc) { US_INFO << "Registering TestModuleBService"; mc->RegisterService(this); } }; class TestModuleBActivator : public ModuleActivator { public: TestModuleBActivator() : s(0) {} ~TestModuleBActivator() { delete s; } void Load(ModuleContext* context) { s = new TestModuleB(context); } void Unload(ModuleContext*) { } private: TestModuleB* s; }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleB, US_PREPEND_NAMESPACE(TestModuleBActivator)) US_IMPORT_MODULE(TestModuleImportedByB) US_IMPORT_MODULE_RESOURCES(TestModuleImportedByB) US_LOAD_IMPORTED_MODULES(TestModuleB, TestModuleImportedByB) diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h rename to Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp similarity index 93% rename from Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp rename to Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp index 34459640f1..8c6008e506 100644 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp +++ b/Core/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp @@ -1,67 +1,65 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usTestModuleBService.h" #include #include #include -#include US_BASECLASS_HEADER US_BEGIN_NAMESPACE -struct TestModuleImportedByB : public US_BASECLASS_NAME, public TestModuleBService +struct TestModuleImportedByB : public TestModuleBService { TestModuleImportedByB(ModuleContext* mc) { US_INFO << "Registering TestModuleImportedByB"; mc->RegisterService(this); } }; class TestModuleImportedByBActivator : public ModuleActivator { public: TestModuleImportedByBActivator() : s(0) {} ~TestModuleImportedByBActivator() { delete s; } void Load(ModuleContext* context) { s = new TestModuleImportedByB(context); } void Unload(ModuleContext*) { } private: TestModuleImportedByB* s; }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleImportedByB, US_PREPEND_NAMESPACE(TestModuleImportedByBActivator)) - diff --git a/Core/CppMicroServices/test/modules/libH/CMakeLists.txt b/Core/CppMicroServices/test/modules/libH/CMakeLists.txt new file mode 100644 index 0000000000..0aa0176b5d --- /dev/null +++ b/Core/CppMicroServices/test/modules/libH/CMakeLists.txt @@ -0,0 +1,2 @@ + +usFunctionCreateTestModule(TestModuleH usTestModuleH.cpp) diff --git a/Core/CppMicroServices/test/modules/libH/usTestModuleH.cpp b/Core/CppMicroServices/test/modules/libH/usTestModuleH.cpp new file mode 100644 index 0000000000..2352c039a4 --- /dev/null +++ b/Core/CppMicroServices/test/modules/libH/usTestModuleH.cpp @@ -0,0 +1,147 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#include +#include +#include +#include +#include +#include + +#include + +US_BEGIN_NAMESPACE + +struct TestModuleH +{ + virtual ~TestModuleH() {} +}; + +struct TestModuleH2 +{ + virtual ~TestModuleH2() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH), "org.cppmicroservices.TestModuleH") +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH2), "org.cppmicroservices.TestModuleH2") + +US_BEGIN_NAMESPACE + +class TestProduct : public TestModuleH +{ + Module* caller; + +public: + + TestProduct(Module* caller) + : caller(caller) + {} + +}; + +class TestProduct2 : public TestProduct, public TestModuleH2 +{ +public: + + TestProduct2(Module* caller) + : TestProduct(caller) + {} + +}; + +class TestModuleHPrototypeServiceFactory : public PrototypeServiceFactory +{ + std::map > fcbind; // Map calling module with implementation + +public: + + InterfaceMap GetService(Module* caller, const ServiceRegistrationBase& /*sReg*/) + { + std::cout << "GetService (prototype) in H" << std::endl; + TestProduct2* product = new TestProduct2(caller); + fcbind[caller->GetModuleId()].push_back(product); + return MakeInterfaceMap(product); + } + + void UngetService(Module* caller, const ServiceRegistrationBase& /*sReg*/, const InterfaceMap& service) + { + TestProduct2* product = dynamic_cast(ExtractInterface(service)); + delete product; + fcbind[caller->GetModuleId()].remove(product); + } + +}; + + +class TestModuleHActivator : public ModuleActivator, public ServiceFactory +{ + std::string thisServiceName; + ServiceRegistration factoryService; + ServiceRegistration prototypeFactoryService; + ModuleContext* mc; + + std::map fcbind; // Map calling module with implementation + TestModuleHPrototypeServiceFactory prototypeFactory; + +public: + + TestModuleHActivator() + : thisServiceName(us_service_interface_iid()) + , mc(NULL) + {} + + void Load(ModuleContext* mc) + { + std::cout << "start in H" << std::endl; + this->mc = mc; + factoryService = mc->RegisterService(this); + prototypeFactoryService = mc->RegisterService(static_cast(&prototypeFactory)); + } + + void Unload(ModuleContext* /*mc*/) + { + factoryService.Unregister(); + } + + InterfaceMap GetService(Module* caller, const ServiceRegistrationBase& /*sReg*/) + { + std::cout << "GetService in H" << std::endl; + TestProduct* product = new TestProduct(caller); + fcbind.insert(std::make_pair(caller->GetModuleId(), product)); + return MakeInterfaceMap(product); + } + + void UngetService(Module* caller, const ServiceRegistrationBase& /*sReg*/, const InterfaceMap& service) + { + TestModuleH* product = ExtractInterface(service); + delete product; + fcbind.erase(caller->GetModuleId()); + } + +}; + + +US_END_NAMESPACE + +US_EXPORT_MODULE_ACTIVATOR(TestModuleH, us::TestModuleHActivator) diff --git a/Core/CppMicroServices/test/modules/libM/CMakeLists.txt b/Core/CppMicroServices/test/modules/libM/CMakeLists.txt new file mode 100644 index 0000000000..c96b103203 --- /dev/null +++ b/Core/CppMicroServices/test/modules/libM/CMakeLists.txt @@ -0,0 +1,8 @@ + +set(resource_files + manifest.json +) + +usFunctionCreateTestModuleWithResources(TestModuleM + SOURCES usTestModuleM.cpp + RESOURCES ${resource_files}) diff --git a/Core/CppMicroServices/test/modules/libM/resources/manifest.json b/Core/CppMicroServices/test/modules/libM/resources/manifest.json new file mode 100644 index 0000000000..c2b05e4708 --- /dev/null +++ b/Core/CppMicroServices/test/modules/libM/resources/manifest.json @@ -0,0 +1,16 @@ +{ + "module.name": "TestModuleM Module", + "module.description": "My Module description", + "module.version": "1.0.0", + "number": 5, + "vector": [ + "first", + 2, + "third" + ], + "map": { + "string": "hi", + "number": 4, + "list": [ "a", "b" ] + } +} diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp b/Core/CppMicroServices/test/modules/libM/usTestModuleM.cpp similarity index 87% copy from Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp copy to Core/CppMicroServices/test/modules/libM/usTestModuleM.cpp index 602caaf82f..934056c84b 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp +++ b/Core/CppMicroServices/test/modules/libM/usTestModuleM.cpp @@ -1,44 +1,43 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include US_BEGIN_NAMESPACE -class TestModuleRActivator : public ModuleActivator +class TestModuleMActivator : public ModuleActivator { public: void Load(ModuleContext*) { } void Unload(ModuleContext*) { } }; US_END_NAMESPACE -US_EXPORT_MODULE_ACTIVATOR(TestModuleR, US_PREPEND_NAMESPACE(TestModuleRActivator)) - +US_EXPORT_MODULE_ACTIVATOR(TestModuleM, US_PREPEND_NAMESPACE(TestModuleMActivator)) diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt b/Core/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt index c39359ab09..e5ff2c8109 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt @@ -1,14 +1,13 @@ set(resource_files icons/compressable.bmp icons/cppmicroservices.png icons/readme.txt foo.txt special_chars.dummy.txt test.xml ) usFunctionCreateTestModuleWithResources(TestModuleR SOURCES usTestModuleR.cpp RESOURCES ${resource_files}) - diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/foo.txt b/Core/CppMicroServices/test/modules/libRWithResources/resources/foo.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/foo.txt rename to Core/CppMicroServices/test/modules/libRWithResources/resources/foo.txt diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp b/Core/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp rename to Core/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png b/Core/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png rename to Core/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt b/Core/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt rename to Core/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt b/Core/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt rename to Core/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml b/Core/CppMicroServices/test/modules/libRWithResources/resources/test.xml similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml rename to Core/CppMicroServices/test/modules/libRWithResources/resources/test.xml index 23208713be..bc90bc6ca9 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml +++ b/Core/CppMicroServices/test/modules/libRWithResources/resources/test.xml @@ -1,4 +1,3 @@ hi - diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp b/Core/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp rename to Core/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp index 602caaf82f..be8c0291ca 100644 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp +++ b/Core/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp @@ -1,44 +1,43 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include US_BEGIN_NAMESPACE class TestModuleRActivator : public ModuleActivator { public: void Load(ModuleContext*) { } void Unload(ModuleContext*) { } }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleR, US_PREPEND_NAMESPACE(TestModuleRActivator)) - diff --git a/Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt b/Core/CppMicroServices/test/modules/libS/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libS/CMakeLists.txt index 1b97fc79ad..cb4ef91bb3 100644 --- a/Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libS/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleS usTestModuleS.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp b/Core/CppMicroServices/test/modules/libS/usTestModuleS.cpp similarity index 83% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp rename to Core/CppMicroServices/test/modules/libS/usTestModuleS.cpp index 6ced8e1eb3..b25ead2668 100644 --- a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp +++ b/Core/CppMicroServices/test/modules/libS/usTestModuleS.cpp @@ -1,137 +1,143 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "../../usServiceControlInterface.h" #include "usTestModuleSService0.h" #include "usTestModuleSService1.h" #include "usTestModuleSService2.h" #include "usTestModuleSService3.h" #include #include #include #include -#include US_BASECLASS_HEADER US_BEGIN_NAMESPACE -class TestModuleS : public US_BASECLASS_NAME, - public ServiceControlInterface, +class TestModuleS : public ServiceControlInterface, public TestModuleSService0, public TestModuleSService1, public TestModuleSService2, public TestModuleSService3 { public: TestModuleS(ModuleContext* mc) : mc(mc) { for(int i = 0; i <= 3; ++i) { - servregs.push_back(ServiceRegistration()); + servregs.push_back(ServiceRegistrationU()); } sreg = mc->RegisterService(this); + sciReg = mc->RegisterService(this); } virtual const char* GetNameOfClass() const { return "TestModuleS"; } void ServiceControl(int offset, const std::string& operation, int ranking) { if (0 <= offset && offset <= 3) { if (operation == "register") { if (!servregs[offset]) { std::stringstream servicename; servicename << SERVICE << offset; + InterfaceMap ifm; + ifm.insert(std::make_pair(servicename.str(), static_cast(this))); ServiceProperties props; props.insert(std::make_pair(ServiceConstants::SERVICE_RANKING(), Any(ranking))); - servregs[offset] = mc->RegisterService(servicename.str().c_str(), this, props); + servregs[offset] = mc->RegisterService(ifm, props); } } if (operation == "unregister") { if (servregs[offset]) { - ServiceRegistration sr1 = servregs[offset]; + ServiceRegistrationU sr1 = servregs[offset]; sr1.Unregister(); servregs[offset] = 0; } } } } void Unregister() { if (sreg) { sreg.Unregister(); } + if (sciReg) + { + sciReg.Unregister(); + } } private: static const std::string SERVICE; // = "org.cppmicroservices.TestModuleSService" ModuleContext* mc; - std::vector servregs; - ServiceRegistration sreg; + std::vector servregs; + ServiceRegistration sreg; + ServiceRegistration sciReg; }; const std::string TestModuleS::SERVICE = "org.cppmicroservices.TestModuleSService"; class TestModuleSActivator : public ModuleActivator { public: TestModuleSActivator() : s(0) {} ~TestModuleSActivator() { delete s; } void Load(ModuleContext* context) { s = new TestModuleS(context); } void Unload(ModuleContext* /*context*/) { #ifndef US_BUILD_SHARED_LIBS s->Unregister(); #endif } private: TestModuleS* s; }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleS, US_PREPEND_NAMESPACE(TestModuleSActivator)) diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService0.h b/Core/CppMicroServices/test/modules/libS/usTestModuleSService0.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService0.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService0.h diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService1.h b/Core/CppMicroServices/test/modules/libS/usTestModuleSService1.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService1.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService1.h diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService2.h b/Core/CppMicroServices/test/modules/libS/usTestModuleSService2.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService2.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService2.h diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService3.h b/Core/CppMicroServices/test/modules/libS/usTestModuleSService3.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService3.h rename to Core/CppMicroServices/test/modules/libS/usTestModuleSService3.h diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt b/Core/CppMicroServices/test/modules/libSL1/CMakeLists.txt similarity index 98% rename from Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libSL1/CMakeLists.txt index caabb07644..29d6d614c3 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libSL1/CMakeLists.txt @@ -1,3 +1,2 @@ usFunctionCreateTestModule(TestModuleSL1 usActivatorSL1.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp b/Core/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp similarity index 77% rename from Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp rename to Core/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp index 70d429e6b2..f7070ce255 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp +++ b/Core/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp @@ -1,108 +1,106 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include "usFooService.h" -#include US_BASECLASS_HEADER - US_BEGIN_NAMESPACE class ActivatorSL1 : - public US_BASECLASS_NAME, public ModuleActivator, public ModulePropsInterface, - public ServiceTrackerCustomizer + public ModuleActivator, public ModulePropsInterface, + public ServiceTrackerCustomizer { public: ActivatorSL1() : tracker(0), context(0) { } ~ActivatorSL1() { delete tracker; } void Load(ModuleContext* context) { this->context = context; - sr = context->RegisterService("ActivatorSL1", this); + InterfaceMap im = MakeInterfaceMap(this); + im.insert(std::make_pair(std::string("ActivatorSL1"), this)); + sr = context->RegisterService(im); delete tracker; tracker = new FooTracker(context, this); tracker->Open(); } void Unload(ModuleContext* /*context*/) { tracker->Close(); } const Properties& GetProperties() const { return props; } - FooService* AddingService(const ServiceReference& reference) + FooService* AddingService(const ServiceReferenceT& reference) { props["serviceAdded"] = true; FooService* fooService = context->GetService(reference); fooService->foo(); return fooService; } - void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) + void ModifiedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) {} - void RemovedService(const ServiceReference& /*reference*/, FooService* /*service*/) + void RemovedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) { props["serviceRemoved"] = true; } private: ModulePropsInterface::Properties props; - ServiceRegistration sr; + ServiceRegistrationU sr; - typedef ServiceTracker FooTracker; + typedef ServiceTracker FooTracker; FooTracker* tracker; ModuleContext* context; }; // ActivatorSL1 US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleSL1, US_PREPEND_NAMESPACE(ActivatorSL1)) - - diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/usFooService.h b/Core/CppMicroServices/test/modules/libSL1/usFooService.h similarity index 100% rename from Core/Code/CppMicroServices/test/modules/libSL1/usFooService.h rename to Core/CppMicroServices/test/modules/libSL1/usFooService.h diff --git a/Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt b/Core/CppMicroServices/test/modules/libSL3/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libSL3/CMakeLists.txt index 6d11053a64..a342806dd6 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libSL3/CMakeLists.txt @@ -1,5 +1,4 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) usFunctionCreateTestModule(TestModuleSL3 usActivatorSL3.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp b/Core/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp similarity index 74% rename from Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp rename to Core/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp index 965b5d4b01..ea5e9a8706 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp +++ b/Core/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp @@ -1,102 +1,100 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include -#include US_BASECLASS_HEADER - US_BEGIN_NAMESPACE class ActivatorSL3 : - public US_BASECLASS_NAME, public ModuleActivator, public ModulePropsInterface, - public ServiceTrackerCustomizer + public ModuleActivator, public ModulePropsInterface, + public ServiceTrackerCustomizer { public: ActivatorSL3() : tracker(0), context(0) {} ~ActivatorSL3() { delete tracker; } void Load(ModuleContext* context) { this->context = context; - sr = context->RegisterService("ActivatorSL3", this); + InterfaceMap im = MakeInterfaceMap(this); + im.insert(std::make_pair(std::string("ActivatorSL3"), this)); + sr = context->RegisterService(im); delete tracker; tracker = new FooTracker(context, this); tracker->Open(); } void Unload(ModuleContext* /*context*/) { tracker->Close(); } const ModulePropsInterface::Properties& GetProperties() const { return props; } - FooService* AddingService(const ServiceReference& reference) + FooService* AddingService(const ServiceReferenceT& reference) { props["serviceAdded"] = true; US_INFO << "SL3: Adding reference =" << reference; - FooService* fooService = context->GetService(reference); + FooService* fooService = context->GetService(reference); fooService->foo(); return fooService; } - void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) + void ModifiedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/) { } - void RemovedService(const ServiceReference& reference, FooService* /*service*/) + void RemovedService(const ServiceReferenceT& reference, FooService* /*service*/) { props["serviceRemoved"] = true; US_INFO << "SL3: Removing reference =" << reference; } private: - typedef ServiceTracker FooTracker; + typedef ServiceTracker FooTracker; FooTracker* tracker; ModuleContext* context; - ServiceRegistration sr; + ServiceRegistrationU sr; ModulePropsInterface::Properties props; }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleSL3, US_PREPEND_NAMESPACE(ActivatorSL3)) - - diff --git a/Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt b/Core/CppMicroServices/test/modules/libSL4/CMakeLists.txt similarity index 99% rename from Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt rename to Core/CppMicroServices/test/modules/libSL4/CMakeLists.txt index b81486fc62..e81e7e6428 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt +++ b/Core/CppMicroServices/test/modules/libSL4/CMakeLists.txt @@ -1,5 +1,4 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) usFunctionCreateTestModule(TestModuleSL4 usActivatorSL4.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp b/Core/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp similarity index 91% rename from Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp rename to Core/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp index a048128d83..4f0aebb814 100644 --- a/Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp +++ b/Core/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp @@ -1,67 +1,65 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include -#include US_BASECLASS_HEADER - US_BEGIN_NAMESPACE class ActivatorSL4 : - public US_BASECLASS_NAME, public ModuleActivator, public FooService + public ModuleActivator, public FooService { public: ~ActivatorSL4() { } void foo() { US_INFO << "TestModuleSL4: Doing foo"; } void Load(ModuleContext* context) { sr = context->RegisterService(this); US_INFO << "TestModuleSL4: Registered " << sr; } void Unload(ModuleContext* /*context*/) { } private: - ServiceRegistration sr; + ServiceRegistration sr; }; US_END_NAMESPACE US_EXPORT_MODULE_ACTIVATOR(TestModuleSL4, US_PREPEND_NAMESPACE(ActivatorSL4)) diff --git a/Core/Code/CppMicroServices/test/usDebugOutputTest.cpp b/Core/CppMicroServices/test/usDebugOutputTest.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/usDebugOutputTest.cpp rename to Core/CppMicroServices/test/usDebugOutputTest.cpp index c3aab61b92..3fcc643854 100644 --- a/Core/Code/CppMicroServices/test/usDebugOutputTest.cpp +++ b/Core/CppMicroServices/test/usDebugOutputTest.cpp @@ -1,100 +1,99 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include "usTestingMacros.h" US_USE_NAMESPACE static int lastMsgType = -1; static std::string lastMsg; void handleMessages(MsgType type, const char* msg) { lastMsgType = type; lastMsg.assign(msg); } void resetLastMsg() { lastMsgType = -1; lastMsg.clear(); } int usDebugOutputTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("DebugOutputTest"); // Use the default message handler { US_DEBUG << "Msg"; US_DEBUG(false) << "Msg"; US_INFO << "Msg"; US_INFO(false) << "Msg"; US_WARN << "Msg"; US_WARN(false) << "Msg"; } US_TEST_CONDITION(lastMsg.empty(), "Testing default message handler"); resetLastMsg(); installMsgHandler(handleMessages); { US_DEBUG << "Msg"; } #if !defined(US_ENABLE_DEBUG_OUTPUT) US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing suppressed debug message") #else US_TEST_CONDITION(lastMsgType == 0 && lastMsg.find("Msg") != std::string::npos, "Testing debug message") #endif resetLastMsg(); { US_DEBUG(false) << "No msg"; } US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing disabled debug message") resetLastMsg(); { US_INFO << "Info msg"; } US_TEST_CONDITION(lastMsgType == 1 && lastMsg.find("Info msg") != std::string::npos, "Testing informational message") resetLastMsg(); { US_WARN << "Warn msg"; } US_TEST_CONDITION(lastMsgType == 2 && lastMsg.find("Warn msg") != std::string::npos, "Testing warning message") resetLastMsg(); // We cannot test US_ERROR since it will call abort(). installMsgHandler(0); { US_INFO << "Info msg"; } US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing message handler reset") US_TEST_END() } - diff --git a/Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp b/Core/CppMicroServices/test/usLDAPFilterTest.cpp similarity index 99% rename from Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp rename to Core/CppMicroServices/test/usLDAPFilterTest.cpp index 7b2f9b2165..f81a4f3bc7 100644 --- a/Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp +++ b/Core/CppMicroServices/test/usLDAPFilterTest.cpp @@ -1,150 +1,149 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include "usTestingMacros.h" #include US_USE_NAMESPACE int TestParsing() { // WELL FORMED Expr try { US_TEST_OUTPUT(<< "Parsing (cn=Babs Jensen)") LDAPFilter ldap( "(cn=Babs Jensen)" ); US_TEST_OUTPUT(<< "Parsing (!(cn=Tim Howes))") ldap = LDAPFilter( "(!(cn=Tim Howes))" ); US_TEST_OUTPUT(<< "Parsing " << std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))") ldap = LDAPFilter( std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))" ); US_TEST_OUTPUT(<< "Parsing (o=univ*of*mich*)") ldap = LDAPFilter( "(o=univ*of*mich*)" ); } catch (const std::invalid_argument& e) { US_TEST_OUTPUT(<< e.what()); return EXIT_FAILURE; } // MALFORMED Expr try { US_TEST_OUTPUT( << "Parsing malformed expr: cn=Babs Jensen)") LDAPFilter ldap( "cn=Babs Jensen)" ); return EXIT_FAILURE; } catch (const std::invalid_argument&) { } return EXIT_SUCCESS; } int TestEvaluate() { // EVALUATE try { LDAPFilter ldap( "(Cn=Babs Jensen)" ); ServiceProperties props; bool eval = false; // Several values props["cn"] = std::string("Babs Jensen"); props["unused"] = std::string("Jansen"); US_TEST_OUTPUT(<< "Evaluating expr: " << ldap.ToString()) eval = ldap.Match(props); if (!eval) { return EXIT_FAILURE; } // WILDCARD ldap = LDAPFilter( "(cn=Babs *)" ); props.clear(); props["cn"] = std::string("Babs Jensen"); US_TEST_OUTPUT(<< "Evaluating wildcard expr: " << ldap.ToString()) eval = ldap.Match(props); if ( !eval ) { return EXIT_FAILURE; } // NOT FOUND ldap = LDAPFilter( "(cn=Babs *)" ); props.clear(); props["unused"] = std::string("New"); US_TEST_OUTPUT(<< "Expr not found test: " << ldap.ToString()) eval = ldap.Match(props); if ( eval ) { return EXIT_FAILURE; } // std::vector with integer values ldap = LDAPFilter( " ( |(cn=Babs *)(sn=1) )" ); props.clear(); std::vector list; list.push_back(std::string("Babs Jensen")); list.push_back(std::string("1")); props["sn"] = list; US_TEST_OUTPUT(<< "Evaluating vector expr: " << ldap.ToString()) eval = ldap.Match(props); if (!eval) { return EXIT_FAILURE; } // wrong case ldap = LDAPFilter( "(cN=Babs *)" ); props.clear(); props["cn"] = std::string("Babs Jensen"); US_TEST_OUTPUT(<< "Evaluating case sensitive expr: " << ldap.ToString()) eval = ldap.MatchCase(props); if (eval) { return EXIT_FAILURE; } } catch (const std::invalid_argument& e) { US_TEST_OUTPUT( << e.what() ) return EXIT_FAILURE; } return EXIT_SUCCESS; } int usLDAPFilterTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("LDAPFilterTest"); US_TEST_CONDITION(TestParsing() == EXIT_SUCCESS, "Parsing LDAP expressions: ") US_TEST_CONDITION(TestEvaluate() == EXIT_SUCCESS, "Evaluating LDAP expressions: ") US_TEST_END() } - diff --git a/Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp b/Core/CppMicroServices/test/usModuleAutoLoadTest.cpp similarity index 92% rename from Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp rename to Core/CppMicroServices/test/usModuleAutoLoadTest.cpp index 0fb0042ca3..db5dae1a76 100644 --- a/Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp +++ b/Core/CppMicroServices/test/usModuleAutoLoadTest.cpp @@ -1,170 +1,176 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include +#include #include -#include "usTestUtilSharedLibrary.h" #include "usTestUtilModuleListener.h" #include "usTestingMacros.h" #include US_USE_NAMESPACE namespace { +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + void testDefaultAutoLoadPath(bool autoLoadEnabled) { ModuleContext* mc = GetModuleContext(); assert(mc); - TestModuleListener listener(mc); + TestModuleListener listener; try { mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); throw; } - SharedLibraryHandle libAL("TestModuleAL"); + SharedLibrary libAL(LIB_PATH, "TestModuleAL"); try { libAL.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } Module* moduleAL = ModuleRegistry::GetModule("TestModuleAL Module"); US_TEST_CONDITION_REQUIRED(moduleAL != NULL, "Test for existing module TestModuleAL") US_TEST_CONDITION(moduleAL->GetName() == "TestModuleAL Module", "Test module name") // check the listeners for events std::vector pEvts; pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL)); Module* moduleAL_1 = ModuleRegistry::GetModule("TestModuleAL_1 Module"); if (autoLoadEnabled) { US_TEST_CONDITION_REQUIRED(moduleAL_1 != NULL, "Test for existing auto-loaded module TestModuleAL_1") US_TEST_CONDITION(moduleAL_1->GetName() == "TestModuleAL_1 Module", "Test module name") pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL_1)); pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL_1)); } else { US_TEST_CONDITION_REQUIRED(moduleAL_1 == NULL, "Test for non-existing auto-loaded module TestModuleAL_1") } pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL)); US_TEST_CONDITION(listener.CheckListenerEvents(pEvts), "Test for unexpected events"); mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); libAL.Unload(); } void testCustomAutoLoadPath() { ModuleContext* mc = GetModuleContext(); assert(mc); - TestModuleListener listener(mc); + TestModuleListener listener; try { mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); throw; } - SharedLibraryHandle libAL2("TestModuleAL2"); + SharedLibrary libAL2(LIB_PATH, "TestModuleAL2"); try { libAL2.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } Module* moduleAL2 = ModuleRegistry::GetModule("TestModuleAL2 Module"); US_TEST_CONDITION_REQUIRED(moduleAL2 != NULL, "Test for existing module TestModuleAL2") US_TEST_CONDITION(moduleAL2->GetName() == "TestModuleAL2 Module", "Test module name") // check the listeners for events std::vector pEvts; pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL2)); Module* moduleAL2_1 = ModuleRegistry::GetModule("TestModuleAL2_1 Module"); #ifdef US_ENABLE_AUTOLOADING_SUPPORT US_TEST_CONDITION_REQUIRED(moduleAL2_1 != NULL, "Test for existing auto-loaded module TestModuleAL2_1") US_TEST_CONDITION(moduleAL2_1->GetName() == "TestModuleAL2_1 Module", "Test module name") pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL2_1)); pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL2_1)); #else US_TEST_CONDITION_REQUIRED(moduleAL2_1 == NULL, "Test for non-existing aut-loaded module TestModuleAL2_1") #endif pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL2)); US_TEST_CONDITION(listener.CheckListenerEvents(pEvts), "Test for unexpected events"); mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); } } // end unnamed namespace int usModuleAutoLoadTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ModuleLoaderTest"); ModuleSettings::SetAutoLoadingEnabled(false); testDefaultAutoLoadPath(false); ModuleSettings::SetAutoLoadingEnabled(true); testDefaultAutoLoadPath(true); testCustomAutoLoadPath(); US_TEST_END() } diff --git a/Core/CppMicroServices/test/usModuleManifestTest.cpp b/Core/CppMicroServices/test/usModuleManifestTest.cpp new file mode 100644 index 0000000000..757a38da59 --- /dev/null +++ b/Core/CppMicroServices/test/usModuleManifestTest.cpp @@ -0,0 +1,96 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +} // end unnamed namespace + +int usModuleManifestTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ModuleManifestTest"); + + SharedLibrary target(LIB_PATH, "TestModuleM"); + + // Start the test target + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " + << e.what() << " + in frameSL02a:FAIL" ); + } + + Module* moduleM = ModuleRegistry::GetModule("TestModuleM Module"); + US_TEST_CONDITION_REQUIRED(moduleM != 0, "Test for existing module TestModuleM") + + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_NAME()).ToString() == "TestModuleM Module", "Module name") + US_TEST_CONDITION(moduleM->GetName() == "TestModuleM Module", "Module name 2") + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_DESCRIPTION()).ToString() == "My Module description", "Module description") + US_TEST_CONDITION(moduleM->GetLocation() == moduleM->GetProperty(Module::PROP_LOCATION()).ToString(), "Module location") + US_TEST_CONDITION(moduleM->GetProperty(Module::PROP_VERSION()).ToString() == "1.0.0", "Module version") + US_TEST_CONDITION(moduleM->GetVersion() == ModuleVersion(1,0,0), "Module version 2") + + Any anyVector = moduleM->GetProperty("vector"); + US_TEST_CONDITION_REQUIRED(anyVector.Type() == typeid(std::vector), "vector type") + std::vector& vec = ref_any_cast >(anyVector); + US_TEST_CONDITION_REQUIRED(vec.size() == 3, "vector size") + US_TEST_CONDITION_REQUIRED(vec[0].Type() == typeid(std::string), "vector 0 type") + US_TEST_CONDITION_REQUIRED(vec[0].ToString() == "first", "vector 0 value") + US_TEST_CONDITION_REQUIRED(vec[1].Type() == typeid(int), "vector 1 type") + US_TEST_CONDITION_REQUIRED(any_cast(vec[1]) == 2, "vector 1 value") + + Any anyMap = moduleM->GetProperty("map"); + US_TEST_CONDITION_REQUIRED(anyMap.Type() == typeid(std::map), "map type") + std::map& m = ref_any_cast >(anyMap); + US_TEST_CONDITION_REQUIRED(m.size() == 3, "map size") + US_TEST_CONDITION_REQUIRED(m["string"].Type() == typeid(std::string), "map 0 type") + US_TEST_CONDITION_REQUIRED(m["string"].ToString() == "hi", "map 0 value") + US_TEST_CONDITION_REQUIRED(m["number"].Type() == typeid(int), "map 1 type") + US_TEST_CONDITION_REQUIRED(any_cast(m["number"]) == 4, "map 1 value") + US_TEST_CONDITION_REQUIRED(m["list"].Type() == typeid(std::vector), "map 2 type") + US_TEST_CONDITION_REQUIRED(any_cast >(m["list"]).size() == 2, "map 2 value size") + + target.Unload(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usModulePropsInterface.h b/Core/CppMicroServices/test/usModulePropsInterface.h similarity index 100% rename from Core/Code/CppMicroServices/test/usModulePropsInterface.h rename to Core/CppMicroServices/test/usModulePropsInterface.h diff --git a/Core/Code/CppMicroServices/test/usModuleResourceTest.cpp b/Core/CppMicroServices/test/usModuleResourceTest.cpp similarity index 95% rename from Core/Code/CppMicroServices/test/usModuleResourceTest.cpp rename to Core/CppMicroServices/test/usModuleResourceTest.cpp index 4185701c8a..ac4fc25cda 100644 --- a/Core/Code/CppMicroServices/test/usModuleResourceTest.cpp +++ b/Core/CppMicroServices/test/usModuleResourceTest.cpp @@ -1,534 +1,542 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include +#include #include -#include "usTestUtilSharedLibrary.h" #include "usTestingMacros.h" #include #include US_USE_NAMESPACE namespace { void checkResourceInfo(const ModuleResource& res, const std::string& path, const std::string& baseName, const std::string& completeBaseName, const std::string& suffix, const std::string& completeSuffix, int size, bool children = false, bool compressed = false) { US_TEST_CONDITION_REQUIRED(res.IsValid(), "Valid resource") US_TEST_CONDITION(res.GetBaseName() == baseName, "GetBaseName()") US_TEST_CONDITION(res.GetChildren().empty() == !children, "No children") US_TEST_CONDITION(res.GetCompleteBaseName() == completeBaseName, "GetCompleteBaseName()") US_TEST_CONDITION(res.GetName() == completeBaseName + "." + suffix, "GetName()") US_TEST_CONDITION(res.GetResourcePath() == path + completeBaseName + "." + suffix, "GetResourcePath()") US_TEST_CONDITION(res.GetPath() == path, "GetPath()") US_TEST_CONDITION(res.GetSize() == size, "Data size") US_TEST_CONDITION(res.GetSuffix() == suffix, "Suffix") US_TEST_CONDITION(res.GetCompleteSuffix() == completeSuffix, "Complete suffix") US_TEST_CONDITION(res.IsCompressed() == compressed, "Compression flag") } void testTextResource(Module* module) { ModuleResource res = module->GetResource("foo.txt"); #ifdef US_PLATFORM_WINDOWS checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); const std::streampos ssize(13); const std::string fileData = "foo and\nbar\n\n"; #else checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); const std::streampos ssize(12); const std::string fileData = "foo and\nbar\n"; #endif ModuleResourceStream rs(res); rs.seekg(0, std::ios::end); US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); rs.seekg(0, std::ios::beg); std::string content; content.reserve(res.GetSize()); char buffer[1024]; while (rs.read(buffer, sizeof(buffer))) { content.append(buffer, sizeof(buffer)); } content.append(buffer, static_cast(rs.gcount())); US_TEST_CONDITION(rs.eof(), "EOF check"); US_TEST_CONDITION(content == fileData, "Resource content"); rs.clear(); rs.seekg(0); US_TEST_CONDITION_REQUIRED(rs.tellg() == std::streampos(0), "Move to start") US_TEST_CONDITION_REQUIRED(rs.good(), "Start re-reading"); std::vector lines; std::string line; while (std::getline(rs, line)) { lines.push_back(line); } US_TEST_CONDITION_REQUIRED(lines.size() > 1, "Number of lines") US_TEST_CONDITION(lines[0] == "foo and", "Check first line") US_TEST_CONDITION(lines[1] == "bar", "Check second line") } void testTextResourceAsBinary(Module* module) { ModuleResource res = module->GetResource("foo.txt"); #ifdef US_PLATFORM_WINDOWS checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); const std::streampos ssize(16); const std::string fileData = "foo and\r\nbar\r\n\r\n"; #else checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); const std::streampos ssize(13); const std::string fileData = "foo and\nbar\n\n"; #endif ModuleResourceStream rs(res, std::ios_base::binary); rs.seekg(0, std::ios::end); US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); rs.seekg(0, std::ios::beg); std::string content; content.reserve(res.GetSize()); char buffer[1024]; while (rs.read(buffer, sizeof(buffer))) { content.append(buffer, sizeof(buffer)); } content.append(buffer, static_cast(rs.gcount())); US_TEST_CONDITION(rs.eof(), "EOF check"); US_TEST_CONDITION(content == fileData, "Resource content"); } #ifdef US_BUILD_SHARED_LIBS void testInvalidResource(Module* module) { ModuleResource res = module->GetResource("invalid"); US_TEST_CONDITION_REQUIRED(res.IsValid() == false, "Check invalid resource") US_TEST_CONDITION(res.GetName().empty(), "Check empty name") US_TEST_CONDITION(res.GetPath().empty(), "Check empty path") US_TEST_CONDITION(res.GetResourcePath().empty(), "Check empty resource path") US_TEST_CONDITION(res.GetBaseName().empty(), "Check empty base name") US_TEST_CONDITION(res.GetCompleteBaseName().empty(), "Check empty complete base name") US_TEST_CONDITION(res.GetSuffix().empty(), "Check empty suffix") US_TEST_CONDITION(res.GetChildren().empty(), "Check empty children") US_TEST_CONDITION(res.GetSize() == 0, "Check zero size") US_TEST_CONDITION(res.GetData() == NULL, "Check NULL data") ModuleResourceStream rs(res); US_TEST_CONDITION(rs.good() == true, "Check invalid resource stream") rs.ignore(); US_TEST_CONDITION(rs.good() == false, "Check invalid resource stream") US_TEST_CONDITION(rs.eof() == true, "Check invalid resource stream") } #endif void testSpecialCharacters(Module* module) { ModuleResource res = module->GetResource("special_chars.dummy.txt"); #ifdef US_PLATFORM_WINDOWS checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 56, false); const std::streampos ssize(54); const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)\n"; #else checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 54, false); const std::streampos ssize(53); const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)"; #endif ModuleResourceStream rs(res); rs.seekg(0, std::ios_base::end); US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); rs.seekg(0, std::ios_base::beg); std::string content; content.reserve(res.GetSize()); char buffer[1024]; while (rs.read(buffer, sizeof(buffer))) { content.append(buffer, sizeof(buffer)); } content.append(buffer, static_cast(rs.gcount())); US_TEST_CONDITION(rs.eof(), "EOF check"); US_TEST_CONDITION(content == fileData, "Resource content"); } void testBinaryResource(Module* module) { ModuleResource res = module->GetResource("/icons/cppmicroservices.png"); checkResourceInfo(res, "/icons/", "cppmicroservices", "cppmicroservices", "png", "png", 2424, false); ModuleResourceStream rs(res, std::ios_base::binary); rs.seekg(0, std::ios_base::end); std::streampos resLength = rs.tellg(); rs.seekg(0); std::ifstream png(CppMicroServices_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/cppmicroservices.png", std::ifstream::in | std::ifstream::binary); US_TEST_CONDITION_REQUIRED(png.is_open(), "Open reference file") png.seekg(0, std::ios_base::end); std::streampos pngLength = png.tellg(); png.seekg(0); US_TEST_CONDITION(res.GetSize() == resLength, "Check resource size") US_TEST_CONDITION_REQUIRED(resLength == pngLength, "Compare sizes") char c1 = 0; char c2 = 0; bool isEqual = true; int count = 0; while (png.get(c1) && rs.get(c2)) { ++count; if (c1 != c2) { isEqual = false; break; } } US_TEST_CONDITION_REQUIRED(count == pngLength, "Check if everything was read"); US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); US_TEST_CONDITION(png.eof(), "EOF check"); } #ifdef US_ENABLE_RESOURCE_COMPRESSION void testCompressedResource(Module* module) { ModuleResource res = module->GetResource("/icons/compressable.bmp"); checkResourceInfo(res, "/icons/", "compressable", "compressable", "bmp", "bmp", 411, false, true); ModuleResourceStream rs(res, std::ios_base::binary); rs.seekg(0, std::ios_base::end); std::streampos resLength = rs.tellg(); rs.seekg(0); std::ifstream bmp(CppMicroServices_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/compressable.bmp", std::ifstream::in | std::ifstream::binary); US_TEST_CONDITION_REQUIRED(bmp.is_open(), "Open reference file") bmp.seekg(0, std::ios_base::end); std::streampos bmpLength = bmp.tellg(); bmp.seekg(0); US_TEST_CONDITION(300122 == resLength, "Check resource size") US_TEST_CONDITION_REQUIRED(resLength == bmpLength, "Compare sizes") char c1 = 0; char c2 = 0; bool isEqual = true; int count = 0; while (bmp.get(c1) && rs.get(c2)) { ++count; if (c1 != c2) { isEqual = false; break; } } US_TEST_CONDITION_REQUIRED(count == bmpLength, "Check if everything was read"); US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); US_TEST_CONDITION(bmp.eof(), "EOF check"); } #endif struct ResourceComparator { bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const { return mr1 < mr2; } }; #ifdef US_BUILD_SHARED_LIBS void testResourceTree(Module* module) { ModuleResource res = module->GetResource(""); US_TEST_CONDITION(res.GetResourcePath() == "/", "Check root file path") US_TEST_CONDITION(res.IsDir() == true, "Check type") std::vector children = res.GetChildren(); std::sort(children.begin(), children.end()); US_TEST_CONDITION_REQUIRED(children.size() == 4, "Check child count") US_TEST_CONDITION(children[0] == "foo.txt", "Check child name") US_TEST_CONDITION(children[1] == "icons", "Check child name") US_TEST_CONDITION(children[2] == "special_chars.dummy.txt", "Check child name") US_TEST_CONDITION(children[3] == "test.xml", "Check child name") ModuleResource readme = module->GetResource("/icons/readme.txt"); US_TEST_CONDITION(readme.IsFile() && readme.GetChildren().empty(), "Check file resource") ModuleResource icons = module->GetResource("icons"); US_TEST_CONDITION(icons.IsDir() && !icons.IsFile() && !icons.GetChildren().empty(), "Check directory resource") children = icons.GetChildren(); US_TEST_CONDITION_REQUIRED(children.size() == 3, "Check icons child count") std::sort(children.begin(), children.end()); US_TEST_CONDITION(children[0] == "compressable.bmp", "Check child name") US_TEST_CONDITION(children[1] == "cppmicroservices.png", "Check child name") US_TEST_CONDITION(children[2] == "readme.txt", "Check child name") ResourceComparator resourceComparator; // find all .txt files std::vector nodes = module->FindResources("", "*.txt", false); std::sort(nodes.begin(), nodes.end(), resourceComparator); US_TEST_CONDITION_REQUIRED(nodes.size() == 2, "Found child count") US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") US_TEST_CONDITION(nodes[1].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") nodes = module->FindResources("", "*.txt", true); std::sort(nodes.begin(), nodes.end(), resourceComparator); US_TEST_CONDITION_REQUIRED(nodes.size() == 3, "Found child count") US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") US_TEST_CONDITION(nodes[1].GetResourcePath() == "/icons/readme.txt", "Check child name") US_TEST_CONDITION(nodes[2].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") // find all resources nodes = module->FindResources("", "", true); US_TEST_CONDITION(nodes.size() == 6, "Total resource number") nodes = module->FindResources("", "**", true); US_TEST_CONDITION(nodes.size() == 6, "Total resource number") // test pattern matching nodes.clear(); nodes = module->FindResources("/icons", "*micro*.png", false); US_TEST_CONDITION(nodes.size() == 1 && nodes[0].GetResourcePath() == "/icons/cppmicroservices.png", "Check file pattern matches") nodes.clear(); nodes = module->FindResources("", "*.txt", true); US_TEST_CONDITION(nodes.size() == 3, "Check recursive pattern matches") } #else void testResourceTree(Module* module) { ModuleResource res = module->GetResource(""); US_TEST_CONDITION(res.GetResourcePath() == "/", "Check root file path") US_TEST_CONDITION(res.IsDir() == true, "Check type") std::vector children = res.GetChildren(); std::sort(children.begin(), children.end()); - US_TEST_CONDITION_REQUIRED(children.size() == 8, "Check child count") + US_TEST_CONDITION_REQUIRED(children.size() == 10, "Check child count") US_TEST_CONDITION(children[0] == "dynamic.txt", "Check dynamic.txt child name") US_TEST_CONDITION(children[1] == "foo.txt", "Check foo.txt child name") US_TEST_CONDITION(children[2] == "icons", "Check icons child name") - US_TEST_CONDITION(children[3] == "res.txt", "Check res.txt child name") - US_TEST_CONDITION(children[4] == "res.txt", "Check res.txt child name") - US_TEST_CONDITION(children[5] == "special_chars.dummy.txt", "Check special_chars.dummy.txt child name") - US_TEST_CONDITION(children[6] == "static.txt", "Check static.txt child name") - US_TEST_CONDITION(children[7] == "test.xml", "Check test.xml child name") + US_TEST_CONDITION(children[3] == "manifest.json", "Check manifest.json child name") + US_TEST_CONDITION(children[4] == "manifest.json", "Check manifest.json child name") + US_TEST_CONDITION(children[5] == "res.txt", "Check res.txt child name") + US_TEST_CONDITION(children[6] == "res.txt", "Check res.txt child name") + US_TEST_CONDITION(children[7] == "special_chars.dummy.txt", "Check special_chars.dummy.txt child name") + US_TEST_CONDITION(children[8] == "static.txt", "Check static.txt child name") + US_TEST_CONDITION(children[9] == "test.xml", "Check test.xml child name") ModuleResource readme = module->GetResource("/icons/readme.txt"); US_TEST_CONDITION(readme.IsFile() && readme.GetChildren().empty(), "Check file resource") ModuleResource icons = module->GetResource("icons"); US_TEST_CONDITION(icons.IsDir() && !icons.IsFile() && !icons.GetChildren().empty(), "Check directory resource") children = icons.GetChildren(); US_TEST_CONDITION_REQUIRED(children.size() == 3, "Check icons child count") std::sort(children.begin(), children.end()); US_TEST_CONDITION(children[0] == "compressable.bmp", "Check child name") US_TEST_CONDITION(children[1] == "cppmicroservices.png", "Check child name") US_TEST_CONDITION(children[2] == "readme.txt", "Check child name") ResourceComparator resourceComparator; // find all .txt files std::vector nodes = module->FindResources("", "*.txt", false); std::sort(nodes.begin(), nodes.end(), resourceComparator); US_TEST_CONDITION_REQUIRED(nodes.size() == 6, "Found child count") US_TEST_CONDITION(nodes[0].GetResourcePath() == "/dynamic.txt", "Check dynamic.txt child name") US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo.txt", "Check child name") US_TEST_CONDITION(nodes[2].GetResourcePath() == "/res.txt", "Check res.txt child name") US_TEST_CONDITION(nodes[3].GetResourcePath() == "/res.txt", "Check res.txt child name") US_TEST_CONDITION(nodes[4].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") US_TEST_CONDITION(nodes[5].GetResourcePath() == "/static.txt", "Check static.txt child name") nodes = module->FindResources("", "*.txt", true); std::sort(nodes.begin(), nodes.end(), resourceComparator); US_TEST_CONDITION_REQUIRED(nodes.size() == 7, "Found child count") US_TEST_CONDITION(nodes[0].GetResourcePath() == "/dynamic.txt", "Check dynamic.txt child name") US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo.txt", "Check child name") US_TEST_CONDITION(nodes[2].GetResourcePath() == "/icons/readme.txt", "Check child name") US_TEST_CONDITION(nodes[3].GetResourcePath() == "/res.txt", "Check res.txt child name") US_TEST_CONDITION(nodes[4].GetResourcePath() == "/res.txt", "Check res.txt child name") US_TEST_CONDITION(nodes[5].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") US_TEST_CONDITION(nodes[6].GetResourcePath() == "/static.txt", "Check static.txt child name") // find all resources nodes = module->FindResources("", "", true); - US_TEST_CONDITION(nodes.size() == 10, "Total resource number") + US_TEST_CONDITION(nodes.size() == 12, "Total resource number") nodes = module->FindResources("", "**", true); - US_TEST_CONDITION(nodes.size() == 10, "Total resource number") + US_TEST_CONDITION(nodes.size() == 12, "Total resource number") // test pattern matching nodes.clear(); nodes = module->FindResources("/icons", "*micro*.png", false); US_TEST_CONDITION(nodes.size() == 1 && nodes[0].GetResourcePath() == "/icons/cppmicroservices.png", "Check file pattern matches") nodes.clear(); nodes = module->FindResources("", "*.txt", true); US_TEST_CONDITION(nodes.size() == 7, "Check recursive pattern matches") } #endif void testResourceOperators(Module* module) { ModuleResource invalid = module->GetResource("invalid"); ModuleResource foo = module->GetResource("foo.txt"); US_TEST_CONDITION_REQUIRED(foo.IsValid() && foo, "Check valid resource") ModuleResource foo2(foo); US_TEST_CONDITION(foo == foo, "Check equality operator") US_TEST_CONDITION(foo == foo2, "Check copy constructor and equality operator") US_TEST_CONDITION(foo != invalid, "Check inequality with invalid resource") ModuleResource xml = module->GetResource("/test.xml"); US_TEST_CONDITION_REQUIRED(xml.IsValid() && xml, "Check valid resource") US_TEST_CONDITION(foo != xml, "Check inequality") US_TEST_CONDITION(foo < xml, "Check operator<") // check operator< by using a set std::set resources; resources.insert(foo); resources.insert(foo); resources.insert(xml); US_TEST_CONDITION(resources.size() == 2, "Check operator< with set") // check hash function specialization US_UNORDERED_SET_TYPE resources2; resources2.insert(foo); resources2.insert(foo); resources2.insert(xml); US_TEST_CONDITION(resources2.size() == 2, "Check operator< with unordered set") // check operator<< std::ostringstream oss; oss << foo; US_TEST_CONDITION(oss.str() == foo.GetResourcePath(), "Check operator<<") } #ifdef US_BUILD_SHARED_LIBS void testResourceFromExecutable(Module* module) { ModuleResource resource = module->GetResource("usTestResource.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid executable resource") std::string line; ModuleResourceStream rs(resource); std::getline(rs, line); US_TEST_CONDITION(line == "meant to be compiled into the test driver", "Check executable resource content") } #endif } // end unnamed namespace int usModuleResourceTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ModuleResourceTest"); ModuleContext* mc = GetModuleContext(); assert(mc); #ifdef US_BUILD_SHARED_LIBS - SharedLibraryHandle libR("TestModuleR"); + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + SharedLibrary libR(LIB_PATH, "TestModuleR"); try { libR.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } Module* moduleR = ModuleRegistry::GetModule("TestModuleR Module"); US_TEST_CONDITION_REQUIRED(moduleR != NULL, "Test for existing module TestModuleR") US_TEST_CONDITION(moduleR->GetName() == "TestModuleR Module", "Test module name") testInvalidResource(moduleR); testResourceFromExecutable(mc->GetModule()); #else Module* moduleR = mc->GetModule(); US_TEST_CONDITION_REQUIRED(moduleR != NULL, "Test for existing module 0") US_TEST_CONDITION(moduleR->GetName() == "CppMicroServices", "Test module name") #endif testResourceTree(moduleR); testResourceOperators(moduleR); testTextResource(moduleR); testTextResourceAsBinary(moduleR); testSpecialCharacters(moduleR); testBinaryResource(moduleR); #ifdef US_ENABLE_RESOURCE_COMPRESSION testCompressedResource(moduleR); #endif #ifdef US_BUILD_SHARED_LIBS ModuleResource foo = moduleR->GetResource("foo.txt"); US_TEST_CONDITION(foo.IsValid() == true, "Valid resource") libR.Unload(); US_TEST_CONDITION(foo.IsValid() == false, "Invalidated resource") US_TEST_CONDITION(foo.GetData() == NULL, "NULL data") #endif US_TEST_END() } diff --git a/Core/Code/CppMicroServices/test/usModuleTest.cpp b/Core/CppMicroServices/test/usModuleTest.cpp similarity index 89% rename from Core/Code/CppMicroServices/test/usModuleTest.cpp rename to Core/CppMicroServices/test/usModuleTest.cpp index 7958a1891e..43ff75ee8d 100644 --- a/Core/Code/CppMicroServices/test/usModuleTest.cpp +++ b/Core/CppMicroServices/test/usModuleTest.cpp @@ -1,317 +1,325 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include #include +#include -#include US_BASECLASS_HEADER - -#include "usTestUtilSharedLibrary.h" #include "usTestUtilModuleListener.h" #include "usTestingMacros.h" +#include "usTestingConfig.h" US_USE_NAMESPACE namespace { +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif // Verify that the same member function pointers registered as listeners // with different receivers works. void frame02a() { ModuleContext* mc = GetModuleContext(); - TestModuleListener listener1(mc); - TestModuleListener listener2(mc); + TestModuleListener listener1; + TestModuleListener listener2; try { mc->RemoveModuleListener(&listener1, &TestModuleListener::ModuleChanged); mc->AddModuleListener(&listener1, &TestModuleListener::ModuleChanged); mc->RemoveModuleListener(&listener2, &TestModuleListener::ModuleChanged); mc->AddModuleListener(&listener2, &TestModuleListener::ModuleChanged); } catch (const std::logic_error& ise) { US_TEST_FAILED_MSG( << "module listener registration failed " << ise.what() << " : frameSL02a:FAIL" ); } - SharedLibraryHandle target("TestModuleA"); + SharedLibrary target(LIB_PATH, "TestModuleA"); +#ifdef US_BUILD_SHARED_LIBS // Start the test target try { target.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() << " + in frameSL02a:FAIL" ); } -#ifdef US_BUILD_SHARED_LIBS Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing module TestModuleA") #endif std::vector pEvts; #ifdef US_BUILD_SHARED_LIBS pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleA)); pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleA)); #endif std::vector seEvts; US_TEST_CONDITION(listener1.CheckListenerEvents(pEvts, seEvts), "Check first module listener") US_TEST_CONDITION(listener2.CheckListenerEvents(pEvts, seEvts), "Check second module listener") mc->RemoveModuleListener(&listener1, &TestModuleListener::ModuleChanged); mc->RemoveModuleListener(&listener2, &TestModuleListener::ModuleChanged); target.Unload(); } // Verify information from the ModuleInfo struct void frame005a(ModuleContext* mc) { Module* m = mc->GetModule(); // check expected headers #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION("CppMicroServicesTestDriver" == m->GetName(), "Test module name"); US_TEST_CONDITION(ModuleVersion(0,1,0) == m->GetVersion(), "Test module version") #else US_TEST_CONDITION("CppMicroServices" == m->GetName(), "Test module name"); - US_TEST_CONDITION(ModuleVersion(0,9,0) == m->GetVersion(), "Test module version") + US_TEST_CONDITION(ModuleVersion(1,99,0) == m->GetVersion(), "Test module version") #endif } // Get context id, location and status of the module void frame010a(ModuleContext* mc) { Module* m = mc->GetModule(); long int contextid = m->GetModuleId(); US_DEBUG << "CONTEXT ID:" << contextid; std::string location = m->GetLocation(); US_DEBUG << "LOCATION:" << location; US_TEST_CONDITION(!location.empty(), "Test for non-empty module location") US_TEST_CONDITION(m->IsLoaded(), "Test for loaded flag") } //---------------------------------------------------------------------------- //Test result of GetService(ServiceReference()). Should throw std::invalid_argument void frame018a(ModuleContext* mc) { try { - US_BASECLASS_NAME* obj = mc->GetService(ServiceReference()); - US_DEBUG << "Got service object = " << us_service_impl_name(obj) << ", expected std::invalid_argument exception"; + mc->GetService(ServiceReferenceU()); + US_DEBUG << "Got service object, expected std::invalid_argument exception"; US_TEST_FAILED_MSG(<< "Got service object, excpected std::invalid_argument exception") } catch (const std::invalid_argument& ) {} catch (...) { US_TEST_FAILED_MSG(<< "Got wrong exception, expected std::invalid_argument") } } // Load libA and check that it exists and that the service it registers exists, // also check that the expected events occur -void frame020a(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libA) +void frame020a(ModuleContext* mc, TestModuleListener& listener, +#ifdef US_BUILD_SHARED_LIBS + SharedLibrary& libA) { try { libA.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } -#ifdef US_BUILD_SHARED_LIBS Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing module TestModuleA") US_TEST_CONDITION(moduleA->GetName() == "TestModuleA Module", "Test module name") +#else + SharedLibrary& /*libA*/) +{ #endif // Check if libA registered the expected service try { - ServiceReference sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); - US_BASECLASS_NAME* o1 = mc->GetService(sr1); - US_TEST_CONDITION(o1 != 0, "Test if service object found"); + ServiceReferenceU sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); + InterfaceMap o1 = mc->GetService(sr1); + US_TEST_CONDITION(!o1.empty(), "Test if service object found"); try { US_TEST_CONDITION(mc->UngetService(sr1), "Test if Service UnGet returns true"); } catch (const std::logic_error le) { US_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) } // check the listeners for events std::vector pEvts; #ifdef US_BUILD_SHARED_LIBS pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleA)); pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleA)); #endif std::vector seEvts; #ifdef US_BUILD_SHARED_LIBS seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, sr1)); #endif US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); } catch (const ServiceException& /*se*/) { US_TEST_FAILED_MSG(<< "test module, expected service not found"); } #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(moduleA->IsLoaded() == true, "Test if loaded correctly"); #endif } // Unload libA and check for correct events -void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libA) +void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibrary& libA) { #ifdef US_BUILD_SHARED_LIBS Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for non-null module") #endif - ServiceReference sr1 + ServiceReferenceU sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); US_TEST_CONDITION(sr1, "Test for valid service reference") try { libA.Unload(); #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(moduleA->IsLoaded() == false, "Test for unloaded state") #endif } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) } std::vector pEvts; #ifdef US_BUILD_SHARED_LIBS pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADING, moduleA)); pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADED, moduleA)); #endif std::vector seEvts; #ifdef US_BUILD_SHARED_LIBS seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, sr1)); #endif US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); } struct LocalListener { void ServiceChanged(const ServiceEvent) {} }; // Add a service listener with a broken LDAP filter to Get an exception void frame045a(ModuleContext* mc) { LocalListener sListen1; std::string brokenFilter = "A broken LDAP filter"; try { mc->AddServiceListener(&sListen1, &LocalListener::ServiceChanged, brokenFilter); } catch (const std::invalid_argument& /*ia*/) { //assertEquals("InvalidSyntaxException.GetFilter should be same as input string", brokenFilter, ise.GetFilter()); } catch (...) { US_TEST_FAILED_MSG(<< "test module, wrong exception on broken LDAP filter:"); } } } // end unnamed namespace int usModuleTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ModuleTest"); frame02a(); ModuleContext* mc = GetModuleContext(); - TestModuleListener listener(mc); + TestModuleListener listener; try { mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); throw; } try { mc->AddServiceListener(&listener, &TestModuleListener::ServiceChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); throw; } frame005a(mc); frame010a(mc); frame018a(mc); - SharedLibraryHandle libA("TestModuleA"); + SharedLibrary libA(LIB_PATH, "TestModuleA"); frame020a(mc, listener, libA); frame030b(mc, listener, libA); frame045a(mc); mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); mc->RemoveServiceListener(&listener, &TestModuleListener::ServiceChanged); US_TEST_END() } diff --git a/Core/Code/CppMicroServices/test/usServiceControlInterface.h b/Core/CppMicroServices/test/usServiceControlInterface.h similarity index 100% rename from Core/Code/CppMicroServices/test/usServiceControlInterface.h rename to Core/CppMicroServices/test/usServiceControlInterface.h diff --git a/Core/CppMicroServices/test/usServiceFactoryTest.cpp b/Core/CppMicroServices/test/usServiceFactoryTest.cpp new file mode 100644 index 0000000000..14c7a8feaa --- /dev/null +++ b/Core/CppMicroServices/test/usServiceFactoryTest.cpp @@ -0,0 +1,234 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include +#include +#include + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +US_USE_NAMESPACE + +namespace { + +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + +} // end unnamed namespace + + +US_BEGIN_NAMESPACE + +struct TestModuleH +{ + virtual ~TestModuleH() {} +}; + +struct TestModuleH2 +{ + virtual ~TestModuleH2() {} +}; + +US_END_NAMESPACE + +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH), "org.cppmicroservices.TestModuleH") +US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleH2), "org.cppmicroservices.TestModuleH2") + + +void TestServiceFactoryModuleScope() +{ + + // Install and start test module H, a service factory and test that the methods + // in that interface works. + + SharedLibrary target(LIB_PATH, "TestModuleH"); + +#ifdef US_BUILD_SHARED_LIBS + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) + } + + Module* moduleH = ModuleRegistry::GetModule("TestModuleH Module"); + US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") + + std::vector registeredRefs = moduleH->GetRegisteredServices(); + US_TEST_CONDITION_REQUIRED(registeredRefs.size() == 2, "# of registered services") + US_TEST_CONDITION(registeredRefs[0].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") + US_TEST_CONDITION(registeredRefs[1].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") +#endif + + ModuleContext* mc = GetModuleContext(); + // Check that a service reference exist + const ServiceReferenceU sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleH"); + US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") + US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") + + InterfaceMap service = mc->GetService(sr1); + US_TEST_CONDITION_REQUIRED(service.size() >= 1, "GetService()") + InterfaceMap::const_iterator serviceIter = service.find("org.cppmicroservices.TestModuleH"); + US_TEST_CONDITION_REQUIRED(serviceIter != service.end(), "GetService()") + US_TEST_CONDITION_REQUIRED(serviceIter->second != NULL, "GetService()") + + InterfaceMap service2 = mc->GetService(sr1); + US_TEST_CONDITION(service == service2, "Same service pointer") + +#ifdef US_BUILD_SHARED_LIBS + std::vector usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") + US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") + + InterfaceMap service3 = moduleH->GetModuleContext()->GetService(sr1); + US_TEST_CONDITION(service != service3, "Different service pointer") + US_TEST_CONDITION(moduleH->GetModuleContext()->UngetService(sr1), "UngetService()") +#endif + + US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1), "ungetService()") + + target.Unload(); +} + +void TestServiceFactoryPrototypeScope() +{ + + // Install and start test module H, a service factory and test that the methods + // in that interface works. + + SharedLibrary target(LIB_PATH, "TestModuleH"); + +#ifdef US_BUILD_SHARED_LIBS + try + { + target.Load(); + } + catch (const std::exception& e) + { + US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) + } + + Module* moduleH = ModuleRegistry::GetModule("TestModuleH Module"); + US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") +#endif + + ModuleContext* mc = GetModuleContext(); + // Check that a service reference exist + const ServiceReference sr1 = mc->GetServiceReference(); + US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") + US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") + + ServiceObjects svcObjects = mc->GetServiceObjects(sr1); + TestModuleH2* prototypeServiceH2 = svcObjects.GetService(); + + const ServiceReferenceU sr1void = mc->GetServiceReference(us_service_interface_iid()); + ServiceObjects svcObjectsVoid = mc->GetServiceObjects(sr1void); + InterfaceMap prototypeServiceH2Void = svcObjectsVoid.GetService(); + US_TEST_CONDITION_REQUIRED(prototypeServiceH2Void.find(us_service_interface_iid()) != prototypeServiceH2Void.end(), + "ServiceObjects::GetService()") + +#ifdef US_BUILD_SHARED_LIBS + // There should be only one service in use + US_TEST_CONDITION_REQUIRED(mc->GetModule()->GetServicesInUse().size() == 1, "services in use") +#endif + + TestModuleH2* moduleScopeService = mc->GetService(sr1); + US_TEST_CONDITION_REQUIRED(moduleScopeService && moduleScopeService != prototypeServiceH2, "GetService()") + + US_TEST_CONDITION_REQUIRED(prototypeServiceH2 != prototypeServiceH2Void.find(us_service_interface_iid())->second, + "GetService()") + + svcObjectsVoid.UngetService(prototypeServiceH2Void); + + TestModuleH2* moduleScopeService2 = mc->GetService(sr1); + US_TEST_CONDITION(moduleScopeService == moduleScopeService2, "Same service pointer") + +#ifdef US_BUILD_SHARED_LIBS + std::vector usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") + US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") +#endif + + std::string filter = "(" + ServiceConstants::SERVICE_ID() + "=" + sr1.GetProperty(ServiceConstants::SERVICE_ID()).ToString() + ")"; + const ServiceReference sr2 = mc->GetServiceReferences(filter).front(); + US_TEST_CONDITION_REQUIRED(sr2, "Service shall be present.") + US_TEST_CONDITION(sr2.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") + US_TEST_CONDITION(any_cast(sr2.GetProperty(ServiceConstants::SERVICE_ID())) == any_cast(sr1.GetProperty(ServiceConstants::SERVICE_ID())), "same service id") + + try + { + svcObjects.UngetService(moduleScopeService2); + US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") + } + catch (const std::invalid_argument&) + { + // this is expected + } + +#ifdef US_BUILD_SHARED_LIBS + // There should still be only one service in use + usedRefs = mc->GetModule()->GetServicesInUse(); + US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") +#endif + + ServiceObjects svcObjects2 = svcObjects; + ServiceObjects svcObjects3 = mc->GetServiceObjects(sr1); + try + { + svcObjects3.UngetService(prototypeServiceH2); + US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") + } + catch (const std::invalid_argument&) + { + // this is expected + } + + svcObjects2.UngetService(prototypeServiceH2); + prototypeServiceH2 = svcObjects2.GetService(); + TestModuleH2* prototypeServiceH2_2 = svcObjects3.GetService(); + + US_TEST_CONDITION_REQUIRED(prototypeServiceH2_2 && prototypeServiceH2_2 != prototypeServiceH2, "prototype service") + + svcObjects2.UngetService(prototypeServiceH2); + svcObjects3.UngetService(prototypeServiceH2_2); + US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1), "ungetService()") + + target.Unload(); +} + +int usServiceFactoryTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceFactoryTest"); + + TestServiceFactoryModuleScope(); + TestServiceFactoryPrototypeScope(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usServiceListenerTest.cpp b/Core/CppMicroServices/test/usServiceListenerTest.cpp similarity index 86% rename from Core/Code/CppMicroServices/test/usServiceListenerTest.cpp rename to Core/CppMicroServices/test/usServiceListenerTest.cpp index c49d2ca0d9..42c6235d70 100644 --- a/Core/Code/CppMicroServices/test/usServiceListenerTest.cpp +++ b/Core/CppMicroServices/test/usServiceListenerTest.cpp @@ -1,561 +1,567 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include +#include #include #include #include - -#include US_BASECLASS_HEADER +#include #include -#include "usTestUtilSharedLibrary.h" - US_USE_NAMESPACE +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + class TestServiceListener { private: - friend bool runLoadUnloadTest(const std::string&, int cnt, SharedLibraryHandle&, + friend bool runLoadUnloadTest(const std::string&, int cnt, SharedLibrary&, const std::vector&); const bool checkUsingModules; std::vector events; bool teststatus; ModuleContext* mc; public: TestServiceListener(ModuleContext* mc, bool checkUsingModules = true) : checkUsingModules(checkUsingModules), events(), teststatus(true), mc(mc) {} bool getTestStatus() const { return teststatus; } void clearEvents() { events.clear(); } bool checkEvents(const std::vector& eventTypes) { if (events.size() != eventTypes.size()) { dumpEvents(eventTypes); return false; } for (std::size_t i=0; i < eventTypes.size(); ++i) { if (eventTypes[i] != events[i].GetType()) { dumpEvents(eventTypes); return false; } } return true; } void serviceChanged(const ServiceEvent evt) { events.push_back(evt); US_TEST_OUTPUT( << "ServiceEvent: " << evt ); if (ServiceEvent::UNREGISTERING == evt.GetType()) { - ServiceReference sr = evt.GetServiceReference(); + ServiceReferenceU sr = evt.GetServiceReference(); // Validate that no module is marked as using the service std::vector usingModules; sr.GetUsingModules(usingModules); if (checkUsingModules && !usingModules.empty()) { teststatus = false; printUsingModules(sr, "*** Using modules (unreg) should be empty but is: "); } // Check if the service can be fetched - US_BASECLASS_NAME* service = mc->GetService(sr); + InterfaceMap service = mc->GetService(sr); sr.GetUsingModules(usingModules); // if (UNREGISTERSERVICE_VALID_DURING_UNREGISTERING) { // In this mode the service shall be obtainable during // unregistration. - if (service == 0) + if (service.empty()) { teststatus = false; US_TEST_OUTPUT( << "*** Service should be available to ServiceListener " << "while handling unregistering event." ); } - US_TEST_OUTPUT( << "Service (unreg): " << us_service_impl_name(service) ); + US_TEST_OUTPUT( << "Service (unreg): " << service.begin()->first << " -> " << service.begin()->second ); if (checkUsingModules && usingModules.size() != 1) { teststatus = false; printUsingModules(sr, "*** One using module expected " "(unreg, after getService), found: "); } else { printUsingModules(sr, "Using modules (unreg, after getService): "); } // } else { // // In this mode the service shall NOT be obtainable during // // unregistration. // if (null!=service) { // teststatus = false; // out.print("*** Service should not be available to ServiceListener " // +"while handling unregistering event."); // } // if (checkUsingBundles && null!=usingBundles) { // teststatus = false; // printUsingBundles(sr, // "*** Using bundles (unreg, after getService), " // +"should be null but is: "); // } else { // printUsingBundles(sr, // "Using bundles (unreg, after getService): null"); // } // } mc->UngetService(sr); // Check that the UNREGISTERING service can not be looked up // using the service registry. try { long sid = any_cast(sr.GetProperty(ServiceConstants::SERVICE_ID())); std::stringstream ss; ss << "(" << ServiceConstants::SERVICE_ID() << "=" << sid << ")"; - std::list srs = mc->GetServiceReferences("", ss.str()); + std::vector srs = mc->GetServiceReferences("", ss.str()); if (srs.empty()) { US_TEST_OUTPUT( << "ServiceReference for UNREGISTERING service is not" " found in the service registry; ok." ); } else { teststatus = false; US_TEST_OUTPUT( << "*** ServiceReference for UNREGISTERING service," << sr << ", not found in the service registry; fail." ); US_TEST_OUTPUT( << "Found the following Service references:") ; - for(std::list::const_iterator sr = srs.begin(); + for(std::vector::const_iterator sr = srs.begin(); sr != srs.end(); ++sr) { US_TEST_OUTPUT( << (*sr) ); } } } catch (const std::exception& e) { teststatus = false; US_TEST_OUTPUT( << "*** Unexpected excpetion when trying to lookup a" " service while it is in state UNREGISTERING: " << e.what() ); } } } - void printUsingModules(const ServiceReference& sr, const std::string& caption) + void printUsingModules(const ServiceReferenceU& sr, const std::string& caption) { std::vector usingModules; sr.GetUsingModules(usingModules); US_TEST_OUTPUT( << (caption.empty() ? "Using modules: " : caption) ); for(std::vector::const_iterator module = usingModules.begin(); module != usingModules.end(); ++module) { US_TEST_OUTPUT( << " -" << (*module) ); } } // Print expected and actual service events. void dumpEvents(const std::vector& eventTypes) { std::size_t max = events.size() > eventTypes.size() ? events.size() : eventTypes.size(); US_TEST_OUTPUT( << "Expected event type -- Actual event" ); for (std::size_t i=0; i < max; ++i) { ServiceEvent evt = i < events.size() ? events[i] : ServiceEvent(); if (i < eventTypes.size()) { US_TEST_OUTPUT( << " " << eventTypes[i] << "--" << evt ); } else { US_TEST_OUTPUT( << " " << "- NONE - " << "--" << evt ); } } } }; // end of class ServiceListener -bool runLoadUnloadTest(const std::string& name, int cnt, SharedLibraryHandle& target, +bool runLoadUnloadTest(const std::string& name, int cnt, SharedLibrary& target, const std::vector& events) { bool teststatus = true; ModuleContext* mc = GetModuleContext(); for (int i = 0; i < cnt && teststatus; ++i) { TestServiceListener sListen(mc); try { mc->AddServiceListener(&sListen, &TestServiceListener::serviceChanged); //mc->AddServiceListener(MessageDelegate1(&sListen, &ServiceListener::serviceChanged)); } catch (const std::logic_error& ise) { teststatus = false; US_TEST_FAILED_MSG( << "service listener registration failed " << ise.what() << " :" << name << ":FAIL" ); } // Start the test target to get a service published. try { target.Load(); } catch (const std::exception& e) { teststatus = false; US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() << " + in " << name << ":FAIL" ); } // Stop the test target to get a service unpublished. try { target.Unload(); } catch (const std::exception& e) { teststatus = false; US_TEST_FAILED_MSG( << "Failed to unload module, got exception: " << e.what() << " + in " << name << ":FAIL" ); } if (teststatus && !sListen.checkEvents(events)) { teststatus = false; US_TEST_FAILED_MSG( << "Service listener event notification error :" << name << ":FAIL" ); } try { mc->RemoveServiceListener(&sListen, &TestServiceListener::serviceChanged); teststatus &= sListen.teststatus; sListen.clearEvents(); } catch (const std::logic_error& ise) { teststatus = false; US_TEST_FAILED_MSG( << "service listener removal failed " << ise.what() << " :" << name << ":FAIL" ); } } return teststatus; } void frameSL02a() { ModuleContext* mc = GetModuleContext(); TestServiceListener listener1(mc); TestServiceListener listener2(mc); try { mc->RemoveServiceListener(&listener1, &TestServiceListener::serviceChanged); mc->AddServiceListener(&listener1, &TestServiceListener::serviceChanged); mc->RemoveServiceListener(&listener2, &TestServiceListener::serviceChanged); mc->AddServiceListener(&listener2, &TestServiceListener::serviceChanged); } catch (const std::logic_error& ise) { US_TEST_FAILED_MSG( << "service listener registration failed " << ise.what() << " : frameSL02a:FAIL" ); } - SharedLibraryHandle target("TestModuleA"); + SharedLibrary target(LIB_PATH, "TestModuleA"); // Start the test target to get a service published. try { target.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() << " + in frameSL02a:FAIL" ); } std::vector events; events.push_back(ServiceEvent::REGISTERED); US_TEST_CONDITION(listener1.checkEvents(events), "Check first service listener") US_TEST_CONDITION(listener2.checkEvents(events), "Check second service listener") mc->RemoveServiceListener(&listener1, &TestServiceListener::serviceChanged); mc->RemoveServiceListener(&listener2, &TestServiceListener::serviceChanged); target.Unload(); } void frameSL05a() { std::vector events; events.push_back(ServiceEvent::REGISTERED); events.push_back(ServiceEvent::UNREGISTERING); - SharedLibraryHandle libA("TestModuleA"); + SharedLibrary libA(LIB_PATH, "TestModuleA"); bool testStatus = runLoadUnloadTest("FrameSL05a", 1, libA, events); US_TEST_CONDITION(testStatus, "FrameSL05a") } void frameSL10a() { std::vector events; events.push_back(ServiceEvent::REGISTERED); events.push_back(ServiceEvent::UNREGISTERING); - SharedLibraryHandle libA2("TestModuleA2"); + SharedLibrary libA2(LIB_PATH, "TestModuleA2"); bool testStatus = runLoadUnloadTest("FrameSL10a", 1, libA2, events); US_TEST_CONDITION(testStatus, "FrameSL10a") } void frameSL25a() { ModuleContext* mc = GetModuleContext(); TestServiceListener sListen(mc, false); try { mc->AddServiceListener(&sListen, &TestServiceListener::serviceChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); throw; } - SharedLibraryHandle libSL1("TestModuleSL1"); - SharedLibraryHandle libSL3("TestModuleSL3"); - SharedLibraryHandle libSL4("TestModuleSL4"); + SharedLibrary libSL1(LIB_PATH, "TestModuleSL1"); + SharedLibrary libSL3(LIB_PATH, "TestModuleSL3"); + SharedLibrary libSL4(LIB_PATH, "TestModuleSL4"); std::vector expectedServiceEventTypes; // Startup expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // at start of libSL1 expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // FooService at start of libSL4 expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // at start of libSL3 // Stop libSL4 expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // FooService at first stop of libSL4 #ifdef US_BUILD_SHARED_LIBS // Shutdown expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // at stop of libSL1 expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // at stop of libSL3 #endif // Start libModuleTestSL1 to ensure that the Service interface is available. try { - US_TEST_OUTPUT( << "Starting libModuleTestSL1: " << libSL1.GetAbsolutePath() ); + US_TEST_OUTPUT( << "Starting libModuleTestSL1: " << libSL1.GetFilePath() ); libSL1.Load(); } catch (const std::exception& e) { US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); throw; } // Start libModuleTestSL4 that will require the serivce interface and publish // us::FooService try { - US_TEST_OUTPUT( << "Starting libModuleTestSL4: " << libSL4.GetAbsolutePath() ); + US_TEST_OUTPUT( << "Starting libModuleTestSL4: " << libSL4.GetFilePath() ); libSL4.Load(); } catch (const std::exception& e) { US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); throw; } // Start libModuleTestSL3 that will require the serivce interface and get the service try { - US_TEST_OUTPUT( << "Starting libModuleTestSL3: " << libSL3.GetAbsolutePath() ); + US_TEST_OUTPUT( << "Starting libModuleTestSL3: " << libSL3.GetFilePath() ); libSL3.Load(); } catch (const std::exception& e) { US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); throw; } // Check that libSL3 has been notified about the FooService. US_TEST_OUTPUT( << "Check that FooService is added to service tracker in libSL3" ); try { - ServiceReference libSL3SR = mc->GetServiceReference("ActivatorSL3"); - US_BASECLASS_NAME* libSL3Activator = mc->GetService(libSL3SR); - US_TEST_CONDITION_REQUIRED(libSL3Activator, "ActivatorSL3 service != 0"); + ServiceReferenceU libSL3SR = mc->GetServiceReference("ActivatorSL3"); + InterfaceMap libSL3Activator = mc->GetService(libSL3SR); + US_TEST_CONDITION_REQUIRED(!libSL3Activator.empty(), "ActivatorSL3 service != 0"); - ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); - US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); + ServiceReference libSL3PropsI(libSL3SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL3PropsI); + US_TEST_CONDITION_REQUIRED(propsInterface, "ModulePropsInterface != 0"); ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); Any serviceAddedField3 = i->second; US_TEST_CONDITION_REQUIRED(!serviceAddedField3.Empty() && any_cast(serviceAddedField3), "libSL3 notified about presence of FooService"); mc->UngetService(libSL3SR); } catch (const ServiceException& se) { US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); } // Check that libSL1 has been notified about the FooService. US_TEST_OUTPUT( << "Check that FooService is added to service tracker in libSL1" ); try { - ServiceReference libSL1SR = mc->GetServiceReference("ActivatorSL1"); - US_BASECLASS_NAME* libSL1Activator = mc->GetService(libSL1SR); - US_TEST_CONDITION_REQUIRED(libSL1Activator, "ActivatorSL1 service != 0"); + ServiceReferenceU libSL1SR = mc->GetServiceReference("ActivatorSL1"); + InterfaceMap libSL1Activator = mc->GetService(libSL1SR); + US_TEST_CONDITION_REQUIRED(!libSL1Activator.empty(), "ActivatorSL1 service != 0"); - ModulePropsInterface* propsInterface = dynamic_cast(libSL1Activator); + ServiceReference libSL1PropsI(libSL1SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL1PropsI); US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); Any serviceAddedField1 = i->second; US_TEST_CONDITION_REQUIRED(!serviceAddedField1.Empty() && any_cast(serviceAddedField1), "libSL1 notified about presence of FooService"); mc->UngetService(libSL1SR); } catch (const ServiceException& se) { US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); } // Stop the service provider: libSL4 try { - US_TEST_OUTPUT( << "Stop libSL4: " << libSL4.GetAbsolutePath() ); + US_TEST_OUTPUT( << "Stop libSL4: " << libSL4.GetFilePath() ); libSL4.Unload(); } catch (const std::exception& e) { US_TEST_OUTPUT( << "Failed to unload module, got exception:" << e.what() ); throw; } // Check that libSL3 has been notified about the removal of FooService. US_TEST_OUTPUT( << "Check that FooService is removed from service tracker in libSL3" ); try { - ServiceReference libSL3SR = mc->GetServiceReference("ActivatorSL3"); - US_BASECLASS_NAME* libSL3Activator = mc->GetService(libSL3SR); - US_TEST_CONDITION_REQUIRED(libSL3Activator, "ActivatorSL3 service != 0"); + ServiceReferenceU libSL3SR = mc->GetServiceReference("ActivatorSL3"); + InterfaceMap libSL3Activator = mc->GetService(libSL3SR); + US_TEST_CONDITION_REQUIRED(!libSL3Activator.empty(), "ActivatorSL3 service != 0"); - ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); + ServiceReference libSL3PropsI(libSL3SR); + ModulePropsInterface* propsInterface = mc->GetService(libSL3PropsI); US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceRemoved"); US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceRemoved"); Any serviceRemovedField3 = i->second; US_TEST_CONDITION(!serviceRemovedField3.Empty() && any_cast(serviceRemovedField3), "libSL3 notified about removal of FooService"); mc->UngetService(libSL3SR); } catch (const ServiceException& se) { US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); } // Stop libSL1 try { - US_TEST_OUTPUT( << "Stop libSL1:" << libSL1.GetAbsolutePath() ); + US_TEST_OUTPUT( << "Stop libSL1:" << libSL1.GetFilePath() ); libSL1.Unload(); } catch (const std::exception& e) { US_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); throw; } // Stop pSL3 try { - US_TEST_OUTPUT( << "Stop libSL3:" << libSL3.GetAbsolutePath() ); + US_TEST_OUTPUT( << "Stop libSL3:" << libSL3.GetFilePath() ); libSL3.Unload(); } catch (const std::exception& e) { US_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); throw; } // Check service events seen by this class US_TEST_OUTPUT( << "Checking ServiceEvents(ServiceListener):" ); if (!sListen.checkEvents(expectedServiceEventTypes)) { US_TEST_FAILED_MSG( << "Service listener event notification error" ); } US_TEST_CONDITION_REQUIRED(sListen.getTestStatus(), "Service listener checks"); try { mc->RemoveServiceListener(&sListen, &TestServiceListener::serviceChanged); sListen.clearEvents(); } catch (const std::logic_error& ise) { US_TEST_FAILED_MSG( << "service listener removal failed: " << ise.what() ); } } int usServiceListenerTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ServiceListenerTest"); frameSL02a(); frameSL05a(); frameSL10a(); frameSL25a(); US_TEST_END() } - diff --git a/Core/CppMicroServices/test/usServiceRegistryPerformanceTest.cpp b/Core/CppMicroServices/test/usServiceRegistryPerformanceTest.cpp new file mode 100644 index 0000000000..8de3197608 --- /dev/null +++ b/Core/CppMicroServices/test/usServiceRegistryPerformanceTest.cpp @@ -0,0 +1,424 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "usTestingMacros.h" + +#include +#include + +US_USE_NAMESPACE + +#ifdef US_PLATFORM_APPLE +#include +#elif defined(US_PLATFORM_POSIX) +#include +#include +#ifndef _POSIX_MONOTONIC_CLOCK +#error Monotonic clock support missing on this POSIX platform +#endif +#elif defined(US_PLATFORM_WINDOWS) +#include +#else +#error High precision timer support nod available on this platform +#endif + +#include + +class HighPrecisionTimer +{ + +public: + + inline HighPrecisionTimer(); + + inline void Start(); + + inline long long ElapsedMilli(); + + inline long long ElapsedMicro(); + +private: + +#ifdef US_PLATFORM_APPLE + static double timeConvert; + uint64_t startTime; +#elif defined(US_PLATFORM_POSIX) + timespec startTime; +#elif defined(US_PLATFORM_WINDOWS) + LARGE_INTEGER timerFrequency; + LARGE_INTEGER startTime; +#endif +}; + +#ifdef US_PLATFORM_APPLE + +double HighPrecisionTimer::timeConvert = 0.0; + +inline HighPrecisionTimer::HighPrecisionTimer() +: startTime(0) +{ + if (timeConvert == 0) + { + mach_timebase_info_data_t timeBase; + mach_timebase_info(&timeBase); + timeConvert = static_cast(timeBase.numer) / static_cast(timeBase.denom) / 1000.0; + } +} + +inline void HighPrecisionTimer::Start() +{ + startTime = mach_absolute_time(); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + uint64_t current = mach_absolute_time(); + return static_cast(current - startTime) * timeConvert / 1000.0; +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + uint64_t current = mach_absolute_time(); + return static_cast(current - startTime) * timeConvert; +} + +#elif defined(US_PLATFORM_POSIX) + +inline HighPrecisionTimer::HighPrecisionTimer() +{ + startTime.tv_nsec = 0; + startTime.tv_sec = 0; +} + +inline void HighPrecisionTimer::Start() +{ + clock_gettime(CLOCK_MONOTONIC, &startTime); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + timespec current; + clock_gettime(CLOCK_MONOTONIC, ¤t); + return (static_cast(current.tv_sec)*1000 + current.tv_nsec/1000/1000) - + (static_cast(startTime.tv_sec)*1000 + startTime.tv_nsec/1000/1000); +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + timespec current; + clock_gettime(CLOCK_MONOTONIC, ¤t); + return (static_cast(current.tv_sec)*1000*1000 + current.tv_nsec/1000) - + (static_cast(startTime.tv_sec)*1000*1000 + startTime.tv_nsec/1000); +} + +#elif defined(US_PLATFORM_WINDOWS) + +inline HighPrecisionTimer::HighPrecisionTimer() +{ + if (!QueryPerformanceFrequency(&timerFrequency)) + throw std::runtime_error("QueryPerformanceFrequency() failed"); +} + +inline void HighPrecisionTimer::Start() +{ + //DWORD_PTR oldmask = SetThreadAffinityMask(GetCurrentThread(), 0); + QueryPerformanceCounter(&startTime); + //SetThreadAffinityMask(GetCurrentThread(), oldmask); +} + +inline long long HighPrecisionTimer::ElapsedMilli() +{ + LARGE_INTEGER current; + QueryPerformanceCounter(¤t); + return (current.QuadPart - startTime.QuadPart) / (timerFrequency.QuadPart / 1000); +} + +inline long long HighPrecisionTimer::ElapsedMicro() +{ + LARGE_INTEGER current; + QueryPerformanceCounter(¤t); + return (current.QuadPart - startTime.QuadPart) / (timerFrequency.QuadPart / (1000*1000)); +} + +#endif + +class MyServiceListener; + +struct IPerfTestService +{ + virtual ~IPerfTestService() {} +}; + +US_DECLARE_SERVICE_INTERFACE(IPerfTestService, "org.cppmicroservices.test.IPerfTestService") + + +class ServiceRegistryPerformanceTest +{ + +private: + + friend class MyServiceListener; + + ModuleContext* mc; + + int nListeners; + int nServices; + + std::size_t nRegistered; + std::size_t nUnregistering; + std::size_t nModified; + + std::vector > regs; + std::vector listeners; + std::vector services; + +public: + + ServiceRegistryPerformanceTest(ModuleContext* context); + + void InitTestCase(); + void CleanupTestCase(); + + void TestAddListeners(); + void TestRegisterServices(); + + void TestModifyServices(); + void TestUnregisterServices(); + +private: + + std::ostream& Log() const + { + return std::cout; + } + + void AddListeners(int n); + void RegisterServices(int n); + void ModifyServices(); + void UnregisterServices(); + +}; + +class MyServiceListener +{ + +private: + + ServiceRegistryPerformanceTest* ts; + +public: + + MyServiceListener(ServiceRegistryPerformanceTest* ts) + : ts(ts) + { + } + + void ServiceChanged(const ServiceEvent ev) + { + switch(ev.GetType()) + { + case ServiceEvent::REGISTERED: + ts->nRegistered++; + break; + case ServiceEvent::UNREGISTERING: + ts->nUnregistering++; + break; + case ServiceEvent::MODIFIED: + ts->nModified++; + break; + default: + break; + } + } +}; + + +ServiceRegistryPerformanceTest::ServiceRegistryPerformanceTest(ModuleContext* context) + : mc(context) + , nListeners(100) + , nServices(1000) + , nRegistered(0) + , nUnregistering(0) + , nModified(0) +{ +} + +void ServiceRegistryPerformanceTest::InitTestCase() +{ + Log() << "Initialize event counters\n"; + + nRegistered = 0; + nUnregistering = 0; + nModified = 0; +} + +void ServiceRegistryPerformanceTest::CleanupTestCase() +{ + Log() << "Remove all service listeners\n"; + + for(std::size_t i = 0; i < listeners.size(); i++) + { + try + { + MyServiceListener* l = listeners[i]; + mc->RemoveServiceListener(l, &MyServiceListener::ServiceChanged); + delete l; + } + catch (const std::exception& e) + { + Log() << e.what(); + } + } + listeners.clear(); +} + +void ServiceRegistryPerformanceTest::TestAddListeners() +{ + AddListeners(nListeners); +} + +void ServiceRegistryPerformanceTest::AddListeners(int n) +{ + Log() << "adding " << n << " service listeners\n"; + for(int i = 0; i < n; i++) + { + MyServiceListener* l = new MyServiceListener(this); + try + { + listeners.push_back(l); + mc->AddServiceListener(l, &MyServiceListener::ServiceChanged, "(perf.service.value>=0)"); + } + catch (const std::exception& e) + { + Log() << e.what(); + } + } + Log() << "listener count=" << listeners.size() << "\n"; +} + +void ServiceRegistryPerformanceTest::TestRegisterServices() +{ + Log() << "Register services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners << ") REGISTERED events\n"; + + Log() << "registering " << nServices << " services, listener count=" << listeners.size() << "\n"; + + HighPrecisionTimer t; + t.Start(); + RegisterServices(nServices); + long long ms = t.ElapsedMilli(); + Log() << "register took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nRegistered, + "# REGISTERED events must be same as # of registered services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::RegisterServices(int n) +{ + class PerfTestService : public IPerfTestService + { + }; + + std::string pid("my.service."); + + for(int i = 0; i < n; i++) + { + ServiceProperties props; + std::stringstream ss; + ss << pid << i; + props["service.pid"] = ss.str(); + props["perf.service.value"] = i+1; + + PerfTestService* service = new PerfTestService(); + services.push_back(service); + ServiceRegistration reg = + mc->RegisterService(service, props); + regs.push_back(reg); + } +} + +void ServiceRegistryPerformanceTest::TestModifyServices() +{ + Log() << "Modify all services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners << ") MODIFIED events\n"; + + HighPrecisionTimer t; + t.Start(); + ModifyServices(); + long long ms = t.ElapsedMilli(); + Log() << "modify took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nModified, + "# MODIFIED events must be same as # of modified services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::ModifyServices() +{ + Log() << "modifying " << regs.size() << " services, listener count=" << listeners.size() << "\n"; + + for(std::size_t i = 0; i < regs.size(); i++) + { + ServiceRegistration reg = regs[i]; + ServiceProperties props; + props["perf.service.value"] = i * 2; + reg.SetProperties(props); + } +} + +void ServiceRegistryPerformanceTest::TestUnregisterServices() +{ + Log() << "Unregister all services, and check that we get #of services (" + << nServices << ") * #of listeners (" << nListeners + << ") UNREGISTERING events\n"; + + HighPrecisionTimer t; + t.Start(); + UnregisterServices(); + long long ms = t.ElapsedMilli(); + Log() << "unregister took " << ms << "ms\n"; + US_TEST_CONDITION_REQUIRED(nServices * listeners.size() == nUnregistering, "# UNREGISTERING events must be same as # of (un)registered services * # of listeners"); +} + +void ServiceRegistryPerformanceTest::UnregisterServices() +{ + Log() << "unregistering " << regs.size() << " services, listener count=" + << listeners.size() << "\n"; + for(std::size_t i = 0; i < regs.size(); i++) + { + ServiceRegistration reg = regs[i]; + reg.Unregister(); + } + regs.clear(); +} + + +int usServiceRegistryPerformanceTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceRegistryPerformanceTest") + + ServiceRegistryPerformanceTest perfTest(GetModuleContext()); + perfTest.InitTestCase(); + perfTest.TestAddListeners(); + perfTest.TestRegisterServices(); + perfTest.TestModifyServices(); + perfTest.TestUnregisterServices(); + perfTest.CleanupTestCase(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp b/Core/CppMicroServices/test/usServiceRegistryTest.cpp similarity index 84% rename from Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp rename to Core/CppMicroServices/test/usServiceRegistryTest.cpp index a2cbdf3507..bd15ed18f2 100644 --- a/Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp +++ b/Core/CppMicroServices/test/usServiceRegistryTest.cpp @@ -1,138 +1,135 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include "usTestingMacros.h" #include #include #include -#include US_BASECLASS_HEADER - #include US_USE_NAMESPACE struct ITestServiceA { virtual ~ITestServiceA() {} }; US_DECLARE_SERVICE_INTERFACE(ITestServiceA, "org.cppmicroservices.testing.ITestServiceA") int TestMultipleServiceRegistrations() { - struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA + struct TestServiceA : public ITestServiceA { }; ModuleContext* context = GetModuleContext(); TestServiceA s1; TestServiceA s2; - ServiceRegistration reg1 = context->RegisterService(&s1); - ServiceRegistration reg2 = context->RegisterService(&s2); + ServiceRegistration reg1 = context->RegisterService(&s1); + ServiceRegistration reg2 = context->RegisterService(&s2); - std::list refs = context->GetServiceReferences(); + std::vector > refs = context->GetServiceReferences(); US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Testing for two registered ITestServiceA services") reg2.Unregister(); refs = context->GetServiceReferences(); US_TEST_CONDITION_REQUIRED(refs.size() == 1, "Testing for one registered ITestServiceA services") reg1.Unregister(); refs = context->GetServiceReferences(); US_TEST_CONDITION_REQUIRED(refs.empty(), "Testing for no ITestServiceA services") return EXIT_SUCCESS; } int TestServicePropertiesUpdate() { - struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA + struct TestServiceA : public ITestServiceA { }; ModuleContext* context = GetModuleContext(); TestServiceA s1; ServiceProperties props; props["string"] = std::string("A std::string"); props["bool"] = false; const char* str = "A const char*"; props["const char*"] = str; - ServiceRegistration reg1 = context->RegisterService(&s1, props); - ServiceReference ref1 = context->GetServiceReference(); + ServiceRegistration reg1 = context->RegisterService(&s1, props); + ServiceReference ref1 = context->GetServiceReference(); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().size() == 1, "Testing service count") US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty("bool")) == false, "Testing bool property") // register second service with higher rank TestServiceA s2; ServiceProperties props2; props2[ServiceConstants::SERVICE_RANKING()] = 50; - ServiceRegistration reg2 = context->RegisterService(&s2, props2); + ServiceRegistration reg2 = context->RegisterService(&s2, props2); // Get the service with the highest rank, this should be s2. - ServiceReference ref2 = context->GetServiceReference(); - TestServiceA* service = dynamic_cast(context->GetService(ref2)); + ServiceReference ref2 = context->GetServiceReference(); + TestServiceA* service = dynamic_cast(context->GetService(ref2)); US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") props["bool"] = true; // change the service ranking props[ServiceConstants::SERVICE_RANKING()] = 100; reg1.SetProperties(props); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().size() == 2, "Testing service count") US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty("bool")) == true, "Testing bool property") US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty(ServiceConstants::SERVICE_RANKING())) == 100, "Testing updated ranking") // Service with the highest ranking should now be s1 service = dynamic_cast(context->GetService(ref1)); US_TEST_CONDITION_REQUIRED(service == &s1, "Testing highest service rank") reg1.Unregister(); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences("").size() == 1, "Testing service count") service = dynamic_cast(context->GetService(ref2)); US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") reg2.Unregister(); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().empty(), "Testing service count") return EXIT_SUCCESS; } int usServiceRegistryTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ServiceRegistryTest"); US_TEST_CONDITION(TestMultipleServiceRegistrations() == EXIT_SUCCESS, "Testing service registrations: ") US_TEST_CONDITION(TestServicePropertiesUpdate() == EXIT_SUCCESS, "Testing service property update: ") US_TEST_END() } - diff --git a/Core/CppMicroServices/test/usServiceTemplateTest.cpp b/Core/CppMicroServices/test/usServiceTemplateTest.cpp new file mode 100644 index 0000000000..783ebfa8d5 --- /dev/null +++ b/Core/CppMicroServices/test/usServiceTemplateTest.cpp @@ -0,0 +1,211 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include +#include +#include +#include + +#include "usTestingMacros.h" + +struct Interface1 {}; +US_DECLARE_SERVICE_INTERFACE(Interface1, "org.cppmicroservices.test.Interface1") +struct Interface2 {}; +US_DECLARE_SERVICE_INTERFACE(Interface2, "org.cppmicroservices.test.Interface2") +struct Interface3 {}; +US_DECLARE_SERVICE_INTERFACE(Interface3, "org.cppmicroservices.test.Interface3") + +struct MyService1 : public Interface1 +{}; + +struct MyService2 : public Interface1, public Interface2 +{}; + +struct MyService3 : public Interface1, public Interface2, public Interface3 +{}; + +struct MyFactory1 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService1* s = new MyService1; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + +struct MyFactory2 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService2* s = new MyService2; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + +struct MyFactory3 : public us::ServiceFactory +{ + std::map m_idToServiceMap; + + virtual us::InterfaceMap GetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/) + { + MyService3* s = new MyService3; + m_idToServiceMap.insert(std::make_pair(module->GetModuleId(), s)); + return us::MakeInterfaceMap(s); + } + + virtual void UngetService(us::Module* module, const us::ServiceRegistrationBase& /*registration*/, + const us::InterfaceMap& service) + { + std::map::iterator iter = m_idToServiceMap.find(module->GetModuleId()); + if (iter != m_idToServiceMap.end()) + { + US_TEST_CONDITION(static_cast(iter->second) == us::ExtractInterface(service), "Compare service pointer") + delete iter->second; + m_idToServiceMap.erase(iter); + } + } +}; + + +US_USE_NAMESPACE + +int usServiceTemplateTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("ServiceTemplateTest"); + + ModuleContext* mc = GetModuleContext(); + + // Register compile tests + MyService1 s1; + MyService2 s2; + MyService3 s3; + + us::ServiceRegistration sr1 = mc->RegisterService(&s1); + us::ServiceRegistration sr2 = mc->RegisterService(&s2); + us::ServiceRegistration sr3 = mc->RegisterService(&s3); + + MyFactory1 f1; + us::ServiceRegistration sfr1 = mc->RegisterService(&f1); + + MyFactory2 f2; + us::ServiceRegistration sfr2 = mc->RegisterService(static_cast(&f2)); + + MyFactory3 f3; + us::ServiceRegistration sfr3 = mc->RegisterService(static_cast(&f3)); + +#ifdef US_BUILD_SHARED_LIBS + US_TEST_CONDITION(mc->GetModule()->GetRegisteredServices().size() == 6, "# of reg services") +#endif + + std::vector > s1refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s1refs.size() == 6, "# of interface1 regs") + std::vector > s2refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s2refs.size() == 4, "# of interface2 regs") + std::vector > s3refs = mc->GetServiceReferences(); + US_TEST_CONDITION(s3refs.size() == 2, "# of interface3 regs") + + Interface1* i1 = mc->GetService(sr1.GetReference()); + US_TEST_CONDITION(i1 == static_cast(&s1), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr1.GetReference()), "unget interface1 ptr") + i1 = mc->GetService(sfr1.GetReference()); + US_TEST_CONDITION(i1 == static_cast(f1.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr1.GetReference()), "unget interface1 factory ptr") + + i1 = mc->GetService(sr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(&s2), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr2.GetReference(InterfaceT())), "unget interface1 ptr") + i1 = mc->GetService(sfr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(f2.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr2.GetReference(InterfaceT())), "unget interface1 factory ptr") + Interface2* i2 = mc->GetService(sr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(&s2), "interface2 ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sr2.GetReference(InterfaceT())), "unget interface2 ptr") + i2 = mc->GetService(sfr2.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(f2.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface2 factory ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr2.GetReference(InterfaceT())), "unget interface2 factory ptr") + + i1 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(&s3), "interface1 ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface1 ptr") + i1 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i1 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface1 factory ptr") + i1 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface1 factory ptr") + i2 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(&s3), "interface2 ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface2 ptr") + i2 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i2 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface2 factory ptr") + i2 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface2 factory ptr") + Interface3* i3 = mc->GetService(sr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i3 == static_cast(&s3), "interface3 ptr") + i3 = NULL; + US_TEST_CONDITION(mc->UngetService(sr3.GetReference(InterfaceT())), "unget interface3 ptr") + i3 = mc->GetService(sfr3.GetReference(InterfaceT())); + US_TEST_CONDITION(i3 == static_cast(f3.m_idToServiceMap[mc->GetModule()->GetModuleId()]), "interface3 factory ptr") + i3 = NULL; + US_TEST_CONDITION(mc->UngetService(sfr3.GetReference(InterfaceT())), "unget interface3 factory ptr") + + sr1.Unregister(); + sr2.Unregister(); + sr3.Unregister(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp b/Core/CppMicroServices/test/usServiceTrackerTest.cpp similarity index 64% rename from Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp rename to Core/CppMicroServices/test/usServiceTrackerTest.cpp index cf1ad82485..d602d4bd02 100644 --- a/Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp +++ b/Core/CppMicroServices/test/usServiceTrackerTest.cpp @@ -1,202 +1,223 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include +#include #include #include #include #include #include - -#include US_BASECLASS_HEADER +#include #include "usServiceControlInterface.h" -#include "usTestUtilSharedLibrary.h" #include US_USE_NAMESPACE +bool CheckConvertibility(const std::vector& refs, + std::vector::const_iterator idBegin, + std::vector::const_iterator idEnd) +{ + std::vector ids; + ids.assign(idBegin, idEnd); + + for (std::vector::const_iterator sri = refs.begin(); + sri != refs.end(); ++sri) + { + for (std::vector::iterator idIter = ids.begin(); + idIter != ids.end(); ++idIter) + { + if (sri->IsConvertibleTo(*idIter)) + { + ids.erase(idIter); + break; + } + } + } + + return ids.empty(); +} + + int usServiceTrackerTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ServiceTrackerTest") +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + ModuleContext* mc = GetModuleContext(); - SharedLibraryHandle libS("TestModuleS"); + SharedLibrary libS(LIB_PATH, "TestModuleS"); +#ifdef US_BUILD_SHARED_LIBS // Start the test target to get a service published. try { libS.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() ); } +#endif // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null std::string s1("org.cppmicroservices.TestModuleSService"); - ServiceReference servref = mc->GetServiceReference(s1 + "0"); + ServiceReferenceU servref = mc->GetServiceReference(s1 + "0"); US_TEST_CONDITION_REQUIRED(servref != 0, "Test if registered service of id org.cppmicroservices.TestModuleSService0"); - ServiceControlInterface* serviceController = mc->GetService(servref); + ServiceReference servCtrlRef = mc->GetServiceReference(); + US_TEST_CONDITION_REQUIRED(servCtrlRef != 0, "Test if constrol service was registered"); + + ServiceControlInterface* serviceController = mc->GetService(servCtrlRef); US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller"); - std::auto_ptr > st1(new ServiceTracker<>(mc, servref)); + std::auto_ptr > st1(new ServiceTracker(mc, servref)); // 2. Check the size method with an unopened service tracker US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Test if size == 0"); // 3. Open the service tracker and see what it finds, // expect to find one instance of the implementation, // "org.cppmicroservices.TestModuleSService0" st1->Open(); - std::string expName = "TestModuleS"; - std::list sa2; + std::vector sa2; st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 1, "Checking ServiceTracker size"); - std::string name(us_service_impl_name(mc->GetService(sa2.front()))); - US_TEST_CONDITION_REQUIRED(name == expName, "Checking service implementation name"); + US_TEST_CONDITION_REQUIRED(s1 + "0" == sa2[0].GetInterfaceId(), "Checking service implementation name"); // 5. Close this service tracker st1->Close(); // 6. Check the size method, now when the servicetracker is closed US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Checking ServiceTracker size"); // 7. Check if we still track anything , we should get null sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.empty(), "Checking ServiceTracker size"); // 8. A new Servicetracker, this time with a filter for the object std::string fs = std::string("(") + ServiceConstants::OBJECTCLASS() + "=" + s1 + "*" + ")"; LDAPFilter f1(fs); - st1.reset(new ServiceTracker<>(mc, f1)); + st1.reset(new ServiceTracker(mc, f1)); // add a service serviceController->ServiceControl(1, "register", 7); // 9. Open the service tracker and see what it finds, // expect to find two instances of references to // "org.cppmicroservices.TestModuleSService*" // i.e. they refer to the same piece of code + std::vector ids; + ids.push_back((s1 + "0")); + ids.push_back((s1 + "1")); + ids.push_back((s1 + "2")); + ids.push_back((s1 + "3")); + st1->Open(); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name(mc->GetService(*i)->GetNameOfClass()); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.begin()+2), "Check for expected interface id [0]"); + US_TEST_CONDITION_REQUIRED(sa2[1].IsConvertibleTo(s1 + "1"), "Check for expected interface id [1]"); // 10. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(2, "register", 1); sa2.clear(); st1->GetServiceReferences(sa2); + US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name(mc->GetService(*i)->GetNameOfClass()); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } + + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.begin()+3), "Check for expected interface id [2]"); // 11. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(3, "register", 2); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 4, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name = mc->GetService(*i)->GetNameOfClass(); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa2, ids.begin(), ids.end()), "Check for expected interface id [3]"); // 12. Get libTestModuleS to unregister one service and see if it disappears serviceController->ServiceControl(3, "unregister", 0); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name = mc->GetService(*i)->GetNameOfClass(); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } // 13. Get the highest ranking service reference, it should have ranking 7 - ServiceReference h1 = st1->GetServiceReference(); + ServiceReferenceU h1 = st1->GetServiceReference(); int rank = any_cast(h1.GetProperty(ServiceConstants::SERVICE_RANKING())); US_TEST_CONDITION_REQUIRED(rank == 7, "Check service rank"); // 14. Get the service of the highest ranked service reference - US_BASECLASS_NAME* o1 = st1->GetService(h1); - US_TEST_CONDITION_REQUIRED(o1 != 0, "Check for non-null service"); + InterfaceMap o1 = st1->GetService(h1); + US_TEST_CONDITION_REQUIRED(!o1.empty(), "Check for non-null service"); // 14a Get the highest ranked service, directly this time - US_BASECLASS_NAME* o3 = st1->GetService(); - US_TEST_CONDITION_REQUIRED(o3 != 0, "Check for non-null service"); + InterfaceMap o3 = st1->GetService(); + US_TEST_CONDITION_REQUIRED(!o3.empty(), "Check for non-null service"); US_TEST_CONDITION_REQUIRED(o1 == o3, "Check for equal service instances"); // 15. Now release the tracking of that service and then try to get it // from the servicetracker, which should yield a null object serviceController->ServiceControl(1, "unregister", 7); - US_BASECLASS_NAME* o2 = st1->GetService(h1); - US_TEST_CONDITION_REQUIRED(o2 == 0, "Checkt that service is null"); + InterfaceMap o2 = st1->GetService(h1); + US_TEST_CONDITION_REQUIRED(o2.empty(), "Checkt that service is null"); // 16. Get all service objects this tracker tracks, it should be 2 - std::list ts1; + std::vector ts1; st1->GetServices(ts1); US_TEST_CONDITION_REQUIRED(ts1.size() == 2, "Check service count"); // 17. Test the remove method. // First register another service, then remove it being tracked serviceController->ServiceControl(1, "register", 7); h1 = st1->GetServiceReference(); - std::list sa3; + std::vector sa3; st1->GetServiceReferences(sa3); US_TEST_CONDITION_REQUIRED(sa3.size() == 3, "Check service reference count"); - for (std::list::const_iterator i = sa3.begin(); i != sa3.end(); ++i) - { - std::string name = mc->GetService(*i)->GetNameOfClass(); - US_TEST_CONDITION_REQUIRED(name == expName, "Checking for expected class name"); - } + US_TEST_CONDITION_REQUIRED(CheckConvertibility(sa3, ids.begin(), ids.begin()+3), "Check for expected interface id [0]"); st1->Remove(h1); // remove tracking on one servref sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Check service reference count"); // 18. Test the addingService method,add a service reference // 19. Test the removedService method, remove a service reference // 20. Test the waitForService method - US_BASECLASS_NAME* o9 = st1->WaitForService(50); - US_TEST_CONDITION_REQUIRED(o9 != 0, "Checking WaitForService method"); + InterfaceMap o9 = st1->WaitForService(50); + US_TEST_CONDITION_REQUIRED(!o9.empty(), "Checking WaitForService method"); US_TEST_END() } diff --git a/Core/CppMicroServices/test/usSharedLibraryTest.cpp b/Core/CppMicroServices/test/usSharedLibraryTest.cpp new file mode 100644 index 0000000000..862ae23479 --- /dev/null +++ b/Core/CppMicroServices/test/usSharedLibraryTest.cpp @@ -0,0 +1,118 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include + +#include "usTestingMacros.h" +#include "usTestingConfig.h" + +#include +#include + +US_USE_NAMESPACE + +int usSharedLibraryTest(int /*argc*/, char* /*argv*/[]) +{ + US_TEST_BEGIN("SharedLibraryTest"); + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = ""; + const std::string LIB_SUFFIX = ".dll"; + const char PATH_SEPARATOR = '\\'; +#elif defined(US_PLATFORM_APPLE) + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = "lib"; + const std::string LIB_SUFFIX = ".dylib"; + const char PATH_SEPARATOR = '/'; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; + const std::string LIB_PREFIX = "lib"; + const std::string LIB_SUFFIX = ".so"; + const char PATH_SEPARATOR = '/'; + +#endif + + const std::string libAFilePath = LIB_PATH + PATH_SEPARATOR + LIB_PREFIX + "TestModuleA" + LIB_SUFFIX; + SharedLibrary lib1(libAFilePath); + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "Absolute file path") + US_TEST_CONDITION(lib1.GetLibraryPath() == LIB_PATH, "Library path") + US_TEST_CONDITION(lib1.GetName() == "TestModuleA", "Name") + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Prefix") + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Suffix") + lib1.SetName("bla"); + US_TEST_CONDITION(lib1.GetName() == "TestModuleA", "Name after SetName()") + lib1.SetLibraryPath("bla"); + US_TEST_CONDITION(lib1.GetLibraryPath() == LIB_PATH, "Library path after SetLibraryPath()") + lib1.SetPrefix("bla"); + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Prefix after SetPrefix()") + lib1.SetSuffix("bla"); + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Suffix after SetSuffix()") + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "File path after setters") + + lib1.SetFilePath("bla"); + US_TEST_CONDITION(lib1.GetFilePath() == "bla", "Invalid file path") + US_TEST_CONDITION(lib1.GetLibraryPath().empty(), "Empty lib path") + US_TEST_CONDITION(lib1.GetName() == "bla", "Invalid file name") + US_TEST_CONDITION(lib1.GetPrefix() == LIB_PREFIX, "Invalid prefix") + US_TEST_CONDITION(lib1.GetSuffix() == LIB_SUFFIX, "Invalid suffix") + + US_TEST_FOR_EXCEPTION(std::runtime_error, lib1.Load()) + US_TEST_CONDITION(lib1.IsLoaded() == false, "Is loaded") + US_TEST_CONDITION(lib1.GetHandle() == NULL, "Handle") + + lib1.SetFilePath(libAFilePath); + lib1.Load(); + US_TEST_CONDITION(lib1.IsLoaded() == true, "Is loaded") + US_TEST_CONDITION(lib1.GetHandle() != NULL, "Handle") + US_TEST_FOR_EXCEPTION(std::logic_error, lib1.Load()) + + lib1.SetFilePath("bla"); + US_TEST_CONDITION(lib1.GetFilePath() == libAFilePath, "File path") + lib1.Unload(); + + + SharedLibrary lib2(LIB_PATH, "TestModuleA"); + US_TEST_CONDITION(lib2.GetFilePath() == libAFilePath, "File path") + lib2.SetPrefix(""); + US_TEST_CONDITION(lib2.GetPrefix().empty(), "Lib prefix") + US_TEST_CONDITION(lib2.GetFilePath() == LIB_PATH + PATH_SEPARATOR + "TestModuleA" + LIB_SUFFIX, "File path") + + SharedLibrary lib3 = lib2; + US_TEST_CONDITION(lib3.GetFilePath() == lib2.GetFilePath(), "Compare file path") + lib3.SetPrefix(LIB_PREFIX); + US_TEST_CONDITION(lib3.GetFilePath() == libAFilePath, "Compare file path") + lib3.Load(); + US_TEST_CONDITION(lib3.IsLoaded(), "lib3 loaded") + US_TEST_CONDITION(!lib2.IsLoaded(), "lib2 not loaded") + lib1 = lib3; + US_TEST_FOR_EXCEPTION(std::logic_error, lib1.Load()) + lib2.SetPrefix(LIB_PREFIX); + lib2.Load(); + + lib3.Unload(); + US_TEST_CONDITION(!lib3.IsLoaded(), "lib3 unloaded") + US_TEST_CONDITION(!lib1.IsLoaded(), "lib3 unloaded") + lib2.Unload(); + lib1.Unload(); + + US_TEST_END() +} diff --git a/Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp b/Core/CppMicroServices/test/usStaticModuleResourceTest.cpp similarity index 95% rename from Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp rename to Core/CppMicroServices/test/usStaticModuleResourceTest.cpp index 2405f4572a..fd068d07c4 100644 --- a/Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp +++ b/Core/CppMicroServices/test/usStaticModuleResourceTest.cpp @@ -1,151 +1,157 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include +#include -#include - -#include "usTestUtilSharedLibrary.h" #include "usTestingMacros.h" +#include "usTestingConfig.h" #include #include US_USE_NAMESPACE namespace { std::string GetResourceContent(const ModuleResource& resource) { std::string line; ModuleResourceStream rs(resource); std::getline(rs, line); return line; } struct ResourceComparator { bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const { return mr1 < mr2; } }; void testResourceOperators(Module* module) { std::vector resources = module->FindResources("", "res.txt", false); US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count") US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources") } void testResourcesWithStaticImport(Module* module) { ModuleResource resource = module->GetResource("res.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource") std::string line = GetResourceContent(resource); US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content") resource = module->GetResource("dynamic.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource") line = GetResourceContent(resource); US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content") resource = module->GetResource("static.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") line = GetResourceContent(resource); US_TEST_CONDITION(line == "static", "Check dynamic resource content") std::vector resources = module->FindResources("", "*.txt", false); std::stable_sort(resources.begin(), resources.end(), ResourceComparator()); #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(resources.size() == 4, "Check imported resource count") line = GetResourceContent(resources[0]); US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") line = GetResourceContent(resources[1]); US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") line = GetResourceContent(resources[2]); US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") line = GetResourceContent(resources[3]); US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") #else US_TEST_CONDITION(resources.size() == 6, "Check imported resource count") line = GetResourceContent(resources[0]); US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") // skip foo.txt line = GetResourceContent(resources[2]); US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") line = GetResourceContent(resources[3]); US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") // skip special_chars.dummy.txt line = GetResourceContent(resources[5]); US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") #endif } } // end unnamed namespace int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("StaticModuleResourceTest"); assert(GetModuleContext()); #ifdef US_BUILD_SHARED_LIBS - SharedLibraryHandle libB("TestModuleB"); + +#ifdef US_PLATFORM_WINDOWS + const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif + + SharedLibrary libB(LIB_PATH, "TestModuleB"); try { libB.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } Module* module = ModuleRegistry::GetModule("TestModuleB Module"); US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB") US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name") #else Module* module = GetModuleContext()->GetModule(); #endif testResourceOperators(module); testResourcesWithStaticImport(module); #ifdef US_BUILD_SHARED_LIBS ModuleResource resource = module->GetResource("static.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") libB.Unload(); US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource") #endif US_TEST_END() } diff --git a/Core/Code/CppMicroServices/test/usStaticModuleTest.cpp b/Core/CppMicroServices/test/usStaticModuleTest.cpp similarity index 85% rename from Core/Code/CppMicroServices/test/usStaticModuleTest.cpp rename to Core/CppMicroServices/test/usStaticModuleTest.cpp index 4baec3fedb..d158c6a742 100644 --- a/Core/Code/CppMicroServices/test/usStaticModuleTest.cpp +++ b/Core/CppMicroServices/test/usStaticModuleTest.cpp @@ -1,187 +1,195 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include #include #include #include +#include -#include US_BASECLASS_HEADER - -#include "usTestUtilSharedLibrary.h" #include "usTestUtilModuleListener.h" #include "usTestingMacros.h" +#include "usTestingConfig.h" US_USE_NAMESPACE namespace { +#ifdef US_PLATFORM_WINDOWS + static const std::string LIB_PATH = US_RUNTIME_OUTPUT_DIRECTORY; +#else + static const std::string LIB_PATH = US_LIBRARY_OUTPUT_DIRECTORY; +#endif // Load libTestModuleB and check that it exists and that the service it registers exists, // also check that the expected events occur -void frame020a(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libB) +void frame020a(ModuleContext* mc, TestModuleListener& listener, +#ifdef US_BUILD_SHARED_LIBS + SharedLibrary& libB) { try { libB.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } -#ifdef US_BUILD_SHARED_LIBS Module* moduleB = ModuleRegistry::GetModule("TestModuleB Module"); US_TEST_CONDITION_REQUIRED(moduleB != 0, "Test for existing module TestModuleB") US_TEST_CONDITION(moduleB->GetName() == "TestModuleB Module", "Test module name") +#else + SharedLibrary& /*libB*/) +{ #endif // Check if libB registered the expected service try { - std::list refs = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); + std::vector refs = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Test that both the service from the shared and imported library are regsitered"); - US_BASECLASS_NAME* o1 = mc->GetService(refs.front()); - US_TEST_CONDITION(o1 != 0, "Test if first service object found"); + InterfaceMap o1 = mc->GetService(refs.front()); + US_TEST_CONDITION(!o1.empty(), "Test if first service object found"); - US_BASECLASS_NAME* o2 = mc->GetService(refs.back()); - US_TEST_CONDITION(o2 != 0, "Test if second service object found"); + InterfaceMap o2 = mc->GetService(refs.back()); + US_TEST_CONDITION(!o2.empty(), "Test if second service object found"); try { US_TEST_CONDITION(mc->UngetService(refs.front()), "Test if Service UnGet for first service returns true"); US_TEST_CONDITION(mc->UngetService(refs.back()), "Test if Service UnGet for second service returns true"); } catch (const std::logic_error le) { US_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) } // check the listeners for events std::vector pEvts; #ifdef US_BUILD_SHARED_LIBS pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleB)); pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleB)); #endif std::vector seEvts; #ifdef US_BUILD_SHARED_LIBS seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, refs.back())); seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, refs.front())); #endif US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); } catch (const ServiceException& /*se*/) { US_TEST_FAILED_MSG(<< "test module, expected service not found"); } #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(moduleB->IsLoaded() == true, "Test if loaded correctly"); #endif } // Unload libB and check for correct events -void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libB) +void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibrary& libB) { #ifdef US_BUILD_SHARED_LIBS Module* moduleB = ModuleRegistry::GetModule("TestModuleB Module"); US_TEST_CONDITION_REQUIRED(moduleB != 0, "Test for non-null module") #endif - std::list refs + std::vector refs = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); US_TEST_CONDITION(refs.front(), "Test for first valid service reference") US_TEST_CONDITION(refs.back(), "Test for second valid service reference") try { libB.Unload(); #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(moduleB->IsLoaded() == false, "Test for unloaded state") #endif } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) } std::vector pEvts; #ifdef US_BUILD_SHARED_LIBS pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADING, moduleB)); pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADED, moduleB)); #endif std::vector seEvts; #ifdef US_BUILD_SHARED_LIBS seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, refs.back())); seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, refs.front())); #endif US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); } } // end unnamed namespace int usStaticModuleTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("StaticModuleTest"); ModuleContext* mc = GetModuleContext(); - TestModuleListener listener(mc); + TestModuleListener listener; try { mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); throw; } try { mc->AddServiceListener(&listener, &TestModuleListener::ServiceChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); throw; } - SharedLibraryHandle libB("TestModuleB"); + SharedLibrary libB(LIB_PATH, "TestModuleB"); frame020a(mc, listener, libB); frame030b(mc, listener, libB); mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); mc->RemoveServiceListener(&listener, &TestModuleListener::ServiceChanged); US_TEST_END() } diff --git a/Core/Code/CppMicroServices/test/usTestManager.cpp b/Core/CppMicroServices/test/usTestManager.cpp similarity index 88% rename from Core/Code/CppMicroServices/test/usTestManager.cpp rename to Core/CppMicroServices/test/usTestManager.cpp index 4d0a2a29a0..100d5b5997 100644 --- a/Core/Code/CppMicroServices/test/usTestManager.cpp +++ b/Core/CppMicroServices/test/usTestManager.cpp @@ -1,78 +1,82 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usTestManager.h" #include "usModuleImport.h" US_BEGIN_NAMESPACE TestManager& TestManager::GetInstance() { static TestManager instance; return instance; } void TestManager::Initialize() { m_FailedTests = 0; m_PassedTests = 0; } int TestManager::NumberOfFailedTests() { return m_FailedTests; } int TestManager::NumberOfPassedTests() { return m_PassedTests; } void TestManager::TestFailed() { m_FailedTests++; } void TestManager::TestPassed() { m_PassedTests++; } US_END_NAMESPACE #ifndef US_BUILD_SHARED_LIBS +US_IMPORT_MODULE_RESOURCES(CppMicroServices) US_IMPORT_MODULE(TestModuleA) US_IMPORT_MODULE(TestModuleA2) US_IMPORT_MODULE(TestModuleB) US_IMPORT_MODULE_RESOURCES(TestModuleB) +US_IMPORT_MODULE(TestModuleH) +US_IMPORT_MODULE(TestModuleM) +US_IMPORT_MODULE_RESOURCES(TestModuleM) US_IMPORT_MODULE(TestModuleR) US_IMPORT_MODULE_RESOURCES(TestModuleR) US_IMPORT_MODULE(TestModuleS) US_IMPORT_MODULE(TestModuleSL1) US_IMPORT_MODULE(TestModuleSL3) US_IMPORT_MODULE(TestModuleSL4) US_LOAD_IMPORTED_MODULES_INTO_MAIN( - TestModuleA TestModuleA2 TestModuleB TestModuleImportedByB TestModuleR - TestModuleS TestModuleSL1 TestModuleSL3 TestModuleSL4 + TestModuleA TestModuleA2 TestModuleB TestModuleImportedByB TestModuleH TestModuleM + TestModuleR TestModuleS TestModuleSL1 TestModuleSL3 TestModuleSL4 ) #endif diff --git a/Core/Code/CppMicroServices/test/usTestManager.h b/Core/CppMicroServices/test/usTestManager.h similarity index 100% rename from Core/Code/CppMicroServices/test/usTestManager.h rename to Core/CppMicroServices/test/usTestManager.h diff --git a/Core/Code/CppMicroServices/test/usTestResource.txt b/Core/CppMicroServices/test/usTestResource.txt similarity index 100% rename from Core/Code/CppMicroServices/test/usTestResource.txt rename to Core/CppMicroServices/test/usTestResource.txt diff --git a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp b/Core/CppMicroServices/test/usTestUtilModuleListener.cpp similarity index 96% rename from Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp rename to Core/CppMicroServices/test/usTestUtilModuleListener.cpp index 2983b0e750..9098708462 100644 --- a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp +++ b/Core/CppMicroServices/test/usTestUtilModuleListener.cpp @@ -1,160 +1,160 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "usTestUtilModuleListener.h" #include "usUtils_p.h" US_BEGIN_NAMESPACE -TestModuleListener::TestModuleListener(ModuleContext* mc) - : mc(mc), serviceEvents(), moduleEvents() +TestModuleListener::TestModuleListener() + : serviceEvents(), moduleEvents() {} void TestModuleListener::ModuleChanged(const ModuleEvent event) { moduleEvents.push_back(event); US_DEBUG << "ModuleEvent:" << event; } void TestModuleListener::ServiceChanged(const ServiceEvent event) { serviceEvents.push_back(event); US_DEBUG << "ServiceEvent:" << event; } ModuleEvent TestModuleListener::GetModuleEvent() const { if (moduleEvents.empty()) { return ModuleEvent(); } return moduleEvents.back(); } ServiceEvent TestModuleListener::GetServiceEvent() const { if (serviceEvents.empty()) { return ServiceEvent(); } return serviceEvents.back(); } bool TestModuleListener::CheckListenerEvents( bool pexp, ModuleEvent::Type ptype, bool sexp, ServiceEvent::Type stype, - Module* moduleX, ServiceReference* servX) + Module* moduleX, ServiceReferenceU* servX) { std::vector pEvts; std::vector seEvts; if (pexp) pEvts.push_back(ModuleEvent(ptype, moduleX)); if (sexp) seEvts.push_back(ServiceEvent(stype, *servX)); return CheckListenerEvents(pEvts, seEvts); } bool TestModuleListener::CheckListenerEvents(const std::vector& pEvts) { bool listenState = true; // assume everything will work if (pEvts.size() != moduleEvents.size()) { listenState = false; US_DEBUG << "*** Module event mismatch: expected " << pEvts.size() << " event(s), found " << moduleEvents.size() << " event(s)."; const std::size_t max = pEvts.size() > moduleEvents.size() ? pEvts.size() : moduleEvents.size(); for (std::size_t i = 0; i < max; ++i) { const ModuleEvent& pE = i < pEvts.size() ? pEvts[i] : ModuleEvent(); const ModuleEvent& pR = i < moduleEvents.size() ? moduleEvents[i] : ModuleEvent(); US_DEBUG << " " << pE << " - " << pR; } } else { for (std::size_t i = 0; i < pEvts.size(); ++i) { const ModuleEvent& pE = pEvts[i]; const ModuleEvent& pR = moduleEvents[i]; if (pE.GetType() != pR.GetType() || pE.GetModule() != pR.GetModule()) { listenState = false; US_DEBUG << "*** Wrong module event: " << pR << " expected " << pE; } } } moduleEvents.clear(); return listenState; } bool TestModuleListener::CheckListenerEvents(const std::vector& seEvts) { bool listenState = true; // assume everything will work if (seEvts.size() != serviceEvents.size()) { listenState = false; US_DEBUG << "*** Service event mismatch: expected " << seEvts.size() << " event(s), found " << serviceEvents.size() << " event(s)."; const std::size_t max = seEvts.size() > serviceEvents.size() ? seEvts.size() : serviceEvents.size(); for (std::size_t i = 0; i < max; ++i) { const ServiceEvent& seE = i < seEvts.size() ? seEvts[i] : ServiceEvent(); const ServiceEvent& seR = i < serviceEvents.size() ? serviceEvents[i] : ServiceEvent(); US_DEBUG << " " << seE << " - " << seR; } } else { for (std::size_t i = 0; i < seEvts.size(); ++i) { const ServiceEvent& seE = seEvts[i]; const ServiceEvent& seR = serviceEvents[i]; if (seE.GetType() != seR.GetType() || (!(seE.GetServiceReference() == seR.GetServiceReference()))) { listenState = false; US_DEBUG << "*** Wrong service event: " << seR << " expected " << seE; } } } serviceEvents.clear(); return listenState; } bool TestModuleListener::CheckListenerEvents( const std::vector& pEvts, const std::vector& seEvts) { if (!CheckListenerEvents(pEvts)) return false; return CheckListenerEvents(seEvts); } US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.h b/Core/CppMicroServices/test/usTestUtilModuleListener.h similarity index 93% rename from Core/Code/CppMicroServices/test/usTestUtilModuleListener.h rename to Core/CppMicroServices/test/usTestUtilModuleListener.h index eadf26a530..825d5a1d68 100644 --- a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.h +++ b/Core/CppMicroServices/test/usTestUtilModuleListener.h @@ -1,70 +1,68 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef USTESTUTILMODULELISTENER_H #define USTESTUTILMODULELISTENER_H #include "usConfig.h" #include "usModuleEvent.h" #include "usServiceEvent.h" US_BEGIN_NAMESPACE class ModuleContext; class TestModuleListener { public: - TestModuleListener(ModuleContext* mc); + TestModuleListener(); void ModuleChanged(const ModuleEvent event); void ServiceChanged(const ServiceEvent event); ModuleEvent GetModuleEvent() const; ServiceEvent GetServiceEvent() const; bool CheckListenerEvents( bool pexp, ModuleEvent::Type ptype, bool sexp, ServiceEvent::Type stype, - Module* moduleX, ServiceReference* servX); + Module* moduleX, ServiceReferenceU* servX); bool CheckListenerEvents(const std::vector& pEvts); bool CheckListenerEvents(const std::vector& seEvts); bool CheckListenerEvents(const std::vector& pEvts, const std::vector& seEvts); private: - ModuleContext* const mc; - std::vector serviceEvents; std::vector moduleEvents; }; US_END_NAMESPACE #endif // USTESTUTILMODULELISTENER_H diff --git a/Core/Code/CppMicroServices/test/usTestingConfig.h.in b/Core/CppMicroServices/test/usTestingConfig.h.in similarity index 100% rename from Core/Code/CppMicroServices/test/usTestingConfig.h.in rename to Core/CppMicroServices/test/usTestingConfig.h.in diff --git a/Core/Code/CppMicroServices/test/usTestingMacros.h b/Core/CppMicroServices/test/usTestingMacros.h similarity index 97% rename from Core/Code/CppMicroServices/test/usTestingMacros.h rename to Core/CppMicroServices/test/usTestingMacros.h index 4dce9000f8..0b85d3769d 100644 --- a/Core/Code/CppMicroServices/test/usTestingMacros.h +++ b/Core/CppMicroServices/test/usTestingMacros.h @@ -1,133 +1,132 @@ /*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include #include #include #include "usTestManager.h" US_BEGIN_NAMESPACE /** \brief Indicate a failed test. */ class TestFailedException : public std::exception { public: TestFailedException() {} }; US_END_NAMESPACE /** * * \brief Output some text without generating a terminating newline. * * */ #define US_TEST_OUTPUT_NO_ENDL(x) \ std::cout x << std::flush; /** \brief Output some text. */ #define US_TEST_OUTPUT(x) \ US_TEST_OUTPUT_NO_ENDL(x << "\n") /** \brief Do some general test preparations. Must be called first in the main test function. */ #define US_TEST_BEGIN(testName) \ std::string usTestName(#testName); \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().Initialize(); \ try { /** \brief Fail and finish test with message MSG */ #define US_TEST_FAILED_MSG(MSG) \ US_TEST_OUTPUT(MSG) \ throw US_PREPEND_NAMESPACE(TestFailedException)(); /** \brief Must be called last in the main test function. */ #define US_TEST_END() \ - } catch (US_PREPEND_NAMESPACE(TestFailedException) ex) { \ + } catch (const US_PREPEND_NAMESPACE(TestFailedException)&) { \ US_TEST_OUTPUT(<< "Further test execution skipped.") \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ - } catch (std::exception ex) { \ - US_TEST_OUTPUT(<< "std::exception occured " << ex.what()) \ + } catch (const std::exception& ex) { \ + US_TEST_OUTPUT(<< "Exception occured " << ex.what()) \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ } \ if (US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfFailedTests() > 0) { \ US_TEST_OUTPUT(<< usTestName << ": [DONE FAILED] , subtests passed: " << \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfPassedTests() << " failed: " << \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfFailedTests() ) \ return EXIT_FAILURE; \ } else { \ US_TEST_OUTPUT(<< usTestName << ": " \ << US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfPassedTests() \ << " tests [DONE PASSED]") \ return EXIT_SUCCESS; \ } #define US_TEST_CONDITION(COND,MSG) \ US_TEST_OUTPUT_NO_ENDL(<< MSG) \ if ( ! (COND) ) { \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ US_TEST_OUTPUT(<< " [FAILED]\n" << "In " << __FILE__ \ << ", line " << __LINE__ \ << ": " #COND " : [FAILED]") \ } else { \ US_TEST_OUTPUT(<< " [PASSED]") \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ } #define US_TEST_CONDITION_REQUIRED(COND,MSG) \ US_TEST_OUTPUT_NO_ENDL(<< MSG) \ if ( ! (COND) ) { \ US_TEST_FAILED_MSG(<< " [FAILED]\n" << " +--> in " << __FILE__ \ << ", line " << __LINE__ \ << ", expression is false: \"" #COND "\"") \ } else { \ US_TEST_OUTPUT(<< " [PASSED]") \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ } /** * \brief Begin block which should be checked for exceptions * * This macro, together with US_TEST_FOR_EXCEPTION_END, can be used * to test whether a code block throws an expected exception. The test FAILS if the * exception is NOT thrown. */ #define US_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ try { #define US_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ US_TEST_OUTPUT( << "Expected an '" << #EXCEPTIONCLASS << "' exception. [FAILED]") \ } \ catch (EXCEPTIONCLASS) { \ US_TEST_OUTPUT(<< "Caught an expected '" << #EXCEPTIONCLASS \ << "' exception. [PASSED]") \ US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ } /** * \brief Simplified version of US_TEST_FOR_EXCEPTION_BEGIN / END for * a single statement */ #define US_TEST_FOR_EXCEPTION(EXCEPTIONCLASS, STATEMENT) \ US_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ STATEMENT ; \ US_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) - diff --git a/Core/Code/CppMicroServices/tools/CMakeLists.txt b/Core/CppMicroServices/tools/CMakeLists.txt similarity index 67% rename from Core/Code/CppMicroServices/tools/CMakeLists.txt rename to Core/CppMicroServices/tools/CMakeLists.txt index 066a9f5207..336f1d20ee 100644 --- a/Core/Code/CppMicroServices/tools/CMakeLists.txt +++ b/Core/CppMicroServices/tools/CMakeLists.txt @@ -1,14 +1,19 @@ include_directories(${US_INCLUDE_DIRS}) add_definitions(-DUS_RCC_EXECUTABLE_NAME=\"${US_RCC_EXECUTABLE_NAME}\") set(srcs usResourceCompiler.cpp) if(US_ENABLE_RESOURCE_COMPRESSION) list(APPEND srcs usResourceCompressor.c) endif() add_executable(${US_RCC_EXECUTABLE_NAME} ${srcs}) if(WIN32) target_link_libraries(${US_RCC_EXECUTABLE_NAME} Shlwapi) endif() + +install(TARGETS ${US_RCC_EXECUTABLE_NAME} + EXPORT ${PROJECT_NAME}Targets + FRAMEWORK DESTINATION . COMPONENT sdk + RUNTIME DESTINATION bin COMPONENT sdk) diff --git a/Core/Code/CppMicroServices/tools/miniz.c b/Core/CppMicroServices/tools/miniz.c similarity index 100% rename from Core/Code/CppMicroServices/tools/miniz.c rename to Core/CppMicroServices/tools/miniz.c diff --git a/Core/Code/CppMicroServices/tools/usResourceCompiler.cpp b/Core/CppMicroServices/tools/usResourceCompiler.cpp similarity index 100% rename from Core/Code/CppMicroServices/tools/usResourceCompiler.cpp rename to Core/CppMicroServices/tools/usResourceCompiler.cpp diff --git a/Core/Code/CppMicroServices/tools/usResourceCompressor.c b/Core/CppMicroServices/tools/usResourceCompressor.c similarity index 100% rename from Core/Code/CppMicroServices/tools/usResourceCompressor.c rename to Core/CppMicroServices/tools/usResourceCompressor.c diff --git a/Core/Code/CppMicroServices/usConfig.h.in b/Core/CppMicroServices/usConfig.h.in similarity index 90% rename from Core/Code/CppMicroServices/usConfig.h.in rename to Core/CppMicroServices/usConfig.h.in index 9489a2ccc3..c855c1047d 100644 --- a/Core/Code/CppMicroServices/usConfig.h.in +++ b/Core/CppMicroServices/usConfig.h.in @@ -1,252 +1,237 @@ /* USCONFIG.h this file is generated. Do not change! */ #ifndef USCONFIG_H #define USCONFIG_H #cmakedefine US_BUILD_SHARED_LIBS #cmakedefine CppMicroServices_EXPORTS #cmakedefine US_ENABLE_AUTOLOADING_SUPPORT #cmakedefine US_ENABLE_THREADING_SUPPORT #cmakedefine US_ENABLE_SERVICE_FACTORY_SUPPORT #cmakedefine US_ENABLE_RESOURCE_COMPRESSION #cmakedefine US_USE_CXX11 +#cmakedefine US_GCC_RTTI_WORKAROUND_NEEDED ///------------------------------------------------------------------- // Version information //------------------------------------------------------------------- #define CppMicroServices_VERSION_MAJOR @CppMicroServices_VERSION_MAJOR@ #define CppMicroServices_VERSION_MINOR @CppMicroServices_VERSION_MINOR@ #define CppMicroServices_VERSION_PATH @CppMicroServices_VERSION_PATCH@ #define CppMicroServices_VERSION @CppMicroServices_VERSION@ #define CppMicroServices_VERSION_STR "@CppMicroServices_VERSION@" ///------------------------------------------------------------------- // Macros used by the unit tests //------------------------------------------------------------------- #define CppMicroServices_SOURCE_DIR "@CppMicroServices_SOURCE_DIR@" ///------------------------------------------------------------------- // Macros for import/export declarations //------------------------------------------------------------------- #if defined(WIN32) #define US_ABI_EXPORT __declspec(dllexport) #define US_ABI_IMPORT __declspec(dllimport) #define US_ABI_LOCAL #else - #if __GNUC__ >= 4 - #define US_ABI_EXPORT __attribute__ ((visibility ("default"))) - #define US_ABI_IMPORT __attribute__ ((visibility ("default"))) - #define US_ABI_LOCAL __attribute__ ((visibility ("hidden"))) - #else - #define US_ABI_EXPORT - #define US_ABI_IMPORT - #define US_ABI_LOCAL - #endif + #define US_ABI_EXPORT __attribute__ ((visibility ("default"))) + #define US_ABI_IMPORT __attribute__ ((visibility ("default"))) + #define US_ABI_LOCAL __attribute__ ((visibility ("hidden"))) #endif #ifdef US_BUILD_SHARED_LIBS // We are building a shared lib #ifdef CppMicroServices_EXPORTS #define US_EXPORT US_ABI_EXPORT #else #define US_EXPORT US_ABI_IMPORT #endif #else // We are building a static lib - #if __GNUC__ >= 4 - // Don't hide RTTI symbols of definitions in the C++ Micro Services - // headers that are included in DSOs with hidden visibility - #define US_EXPORT US_ABI_EXPORT - #else - #define US_EXPORT - #endif + // Don't hide RTTI symbols of definitions in the C++ Micro Services + // headers that are included in DSOs with hidden visibility + #define US_EXPORT US_ABI_EXPORT #endif //------------------------------------------------------------------- // Namespace customization //------------------------------------------------------------------- #define US_NAMESPACE @US_NAMESPACE@ #ifndef US_NAMESPACE /* user namespace */ # define US_PREPEND_NAMESPACE(name) ::name # define US_USE_NAMESPACE # define US_BEGIN_NAMESPACE # define US_END_NAMESPACE # define US_FORWARD_DECLARE_CLASS(name) class name; # define US_FORWARD_DECLARE_STRUCT(name) struct name; #else /* user namespace */ # define US_PREPEND_NAMESPACE(name) ::US_NAMESPACE::name # define US_USE_NAMESPACE using namespace ::US_NAMESPACE; # define US_BEGIN_NAMESPACE namespace US_NAMESPACE { # define US_END_NAMESPACE } # define US_FORWARD_DECLARE_CLASS(name) \ US_BEGIN_NAMESPACE class name; US_END_NAMESPACE # define US_FORWARD_DECLARE_STRUCT(name) \ US_BEGIN_NAMESPACE struct name; US_END_NAMESPACE namespace US_NAMESPACE {} #endif /* user namespace */ -#define US_BASECLASS_NAME @US_BASECLASS_NAME@ -#define US_BASECLASS_HEADER <@US_BASECLASS_HEADER@> - -// base class forward declaration -@US_BASECLASS_FORWARD_DECLARATION@ - //------------------------------------------------------------------- // Platform defines //------------------------------------------------------------------- #if defined(__APPLE__) #define US_PLATFORM_APPLE #endif #if defined(__linux__) #define US_PLATFORM_LINUX #endif #if defined(_WIN32) || defined(_WIN64) #define US_PLATFORM_WINDOWS #else #define US_PLATFORM_POSIX #endif //------------------------------------------------------------------- // Macros for suppressing warnings //------------------------------------------------------------------- #ifdef _MSC_VER #define US_MSVC_PUSH_DISABLE_WARNING(wn) \ __pragma(warning(push)) \ __pragma(warning(disable:wn)) #define US_MSVC_POP_WARNING \ __pragma(warning(pop)) #define US_MSVC_DISABLE_WARNING(wn) \ __pragma(warning(disable:wn)) #else #define US_MSVC_PUSH_DISABLE_WARNING(wn) #define US_MSVC_POP_WARNING #define US_MSVC_DISABLE_WARNING(wn) #endif // Do not warn about the usage of deprecated unsafe functions US_MSVC_DISABLE_WARNING(4996) //------------------------------------------------------------------- // Debuging & Logging //------------------------------------------------------------------- #cmakedefine US_ENABLE_DEBUG_OUTPUT US_BEGIN_NAMESPACE enum MsgType { DebugMsg = 0, InfoMsg = 1, WarningMsg = 2, ErrorMsg = 3 }; typedef void (*MsgHandler)(MsgType, const char *); US_EXPORT MsgHandler installMsgHandler(MsgHandler); US_END_NAMESPACE //------------------------------------------------------------------- // Hash Container //------------------------------------------------------------------- #ifdef US_USE_CXX11 #include #include #define US_HASH_FUNCTION_BEGIN(type) \ template<> \ struct hash : std::unary_function { \ std::size_t operator()(const type& arg) const { #define US_HASH_FUNCTION_END } }; #define US_HASH_FUNCTION(type, arg) hash()(arg) #if defined(US_PLATFORM_WINDOWS) && (_MSC_VER < 1700) #define US_HASH_FUNCTION_FRIEND(type) friend class ::std::hash #else #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::hash #endif #define US_UNORDERED_MAP_TYPE ::std::unordered_map #define US_UNORDERED_SET_TYPE ::std::unordered_set #define US_HASH_FUNCTION_NAMESPACE ::std #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { #define US_HASH_FUNCTION_NAMESPACE_END } #elif defined(__GNUC__) #include #include #define US_HASH_FUNCTION_BEGIN(type) \ template<> \ struct hash : std::unary_function { \ std::size_t operator()(const type& arg) const { #define US_HASH_FUNCTION_END } }; #define US_HASH_FUNCTION(type, arg) hash()(arg) #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::tr1::hash #define US_UNORDERED_MAP_TYPE ::std::tr1::unordered_map #define US_UNORDERED_SET_TYPE ::std::tr1::unordered_set #define US_HASH_FUNCTION_NAMESPACE ::std::tr1 #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { namespace tr1 { #define US_HASH_FUNCTION_NAMESPACE_END }} #elif _MSC_VER <= 1500 // Visual Studio 2008 and lower #include #include #define US_HASH_FUNCTION_BEGIN(type) \ template<> \ inline std::size_t hash_value(const type& arg) { #define US_HASH_FUNCTION_END } #define US_HASH_FUNCTION(type, arg) hash_value(arg) #define US_HASH_FUNCTION_FRIEND(type) friend std::size_t stdext::hash_value(const type&) #define US_UNORDERED_MAP_TYPE ::stdext::hash_map #define US_UNORDERED_SET_TYPE ::stdext::hash_set #define US_HASH_FUNCTION_NAMESPACE ::stdext #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace stdext { #define US_HASH_FUNCTION_NAMESPACE_END } #endif //------------------------------------------------------------------- // Threading Configuration //------------------------------------------------------------------- #ifdef US_ENABLE_THREADING_SUPPORT #define US_DEFAULT_THREADING US_PREPEND_NAMESPACE(MultiThreaded) #else #define US_DEFAULT_THREADING US_PREPEND_NAMESPACE(SingleThreaded) #endif //------------------------------------------------------------------- // Header Availability //------------------------------------------------------------------- #cmakedefine HAVE_STDINT #endif // USCONFIG_H